This topic describes how to determine whether an object exists using the OSS SDK for Python V2.
Notes
The sample code in this topic uses the
cn-hangzhouregion ID for the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about OSS regions and endpoints, see OSS regions and endpoints.The
oss:GetObjectpermission is required to determine whether an object exists. For more information, see Attach a custom policy to a RAM user.
Method definition
is_object_exist(bucket: str, key: str, version_id: str | None = None, request_payer: str | None = None, **kwargs) → boolRequest parameters
Parameter | Type | Description |
bucket | str | The name of the bucket. |
key | str | The name of the object. |
version_id | str | (Optional) The version ID of the object. |
Return values
Type | Description |
bool | Specifies whether the object exists. |
For the complete definition of this method, see is_object_exist.
Sample code
You can use the following code to determine whether an object exists.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="Check if an object exists in a specified OSS bucket")
# Add the required command-line parameters.
parser.add_argument('--region', help='The region where the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket to check.', required=True)
parser.add_argument('--endpoint', help='Optional: The endpoint URL for the OSS service. If not provided, the default endpoint will be used.')
parser.add_argument('--key', help='The key (or name) of the object to check for existence.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load authentication credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations provided by the SDK and set the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Update the region in the configuration based on user input.
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client instance.
client = oss.Client(cfg)
# Call the is_object_exist method to check whether the specified object exists in the specified bucket.
result = client.is_object_exist(
bucket=args.bucket,
key=args.key,
)
# Print whether the object exists.
print(f'Object exists: {result}')
# Execute the main function when the script is run directly.
if __name__ == "__main__":
main()
References
For the complete sample code to determine whether an object exists, see is_object_exist.py.