Este tópico descreve como verificar se um objeto existe.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Se precisar acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints do OSS, consulte Regions and endpoints.
Neste tópico, você obtém as credenciais de acesso a partir de variáveis de ambiente. Para obter orientações sobre como configurar as credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Se precisar de configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization.
Você precisa ter a permissão
oss:GetObjectpara verificar se um objeto existe. Para obter mais informações, consulte Grant a custom policy.
Exemplos
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Specify the full path of the object. Do not include the bucket name in the full path.
exist = bucket.object_exists('exampleobject.txt')
# If the returned value is true, the specified object exists. If the returned value is false, the specified object does not exist.
if exist:
print('object exist')
else:
print('object not exist')