Todos os produtos
Search
Central de documentação

Object Storage Service:Verificar se um objeto existe usando o OSS SDK for Java

Última atualização: Sep 25, 2026

Este tópico descreve como verificar se um objeto existe usando o OSS SDK for Python.

Observações

  • O código de exemplo deste tópico usa o ID de região cn-hangzhou, da região China (Hangzhou). Por padrão, use o endpoint público para acessar recursos em um bucket. Se precisar acessar os recursos do bucket com outros serviços do Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre OSS regions and endpoints.

  • A permissão oss:GetObject é necessária para verificar a existência de objetos. Para obter mais informações, consulte Grant a custom policy.

Método

is_object_exist(bucket: str, key: str, version_id: str | None = None, request_payer: str | None = None, **kwargs) → bool

Parâmetros da requisição

Parâmetro

Tipo

Descrição

bucket

str

Nome do bucket.

key

str

Nome do objeto.

version_id

str

ID de versão do objeto (opcional).

Parâmetros de resposta

Tipo

Descrição

bool

Indica se um objeto existe.

Para obter detalhes sobre este método, consulte is_object_exist.

Código de exemplo

Veja a seguir um exemplo de código para verificar a existência de um objeto.

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")
# Specify the 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 parameters.
    args = parser.parse_args()

    # Load access credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Update the region parameter based on the 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 bucket.
    result = client.is_object_exist(
        bucket=args.bucket,
        key=args.key,
    )

    # Output the result.
    print(f'Object exists: {result}')

# Entry point of the script. The main function is invoked when the file is run directly.
if __name__ == "__main__":
    main()

Referência

  • Para acessar o código de exemplo completo usado para verificar se um objeto existe, visite is_object_exist.py.