Todos os produtos
Search
Central de documentação

Object Storage Service:Consultar a região de um bucket (Python SDK V2)

Última atualização: Jul 03, 2026

Este tópico descreve como consultar a região de um bucket com o OSS SDK for Python V2.

Observações

  • O código de exemplo deste tópico usa o ID de região cn-hangzhou para a região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre via endpoint público. Para acessar os recursos do bucket 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 endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber mais sobre a configuração de credenciais de acesso, consulte Configurar credenciais de acesso.

  • A consulta à região de um bucket exige a permissão oss:GetBucketLocation. Para mais detalhes, consulte Conceder políticas personalizadas a usuários do RAM.

Definição do método

get_bucket_location(request: GetBucketLocationRequest, **kwargs) → GetBucketLocationResult

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

request

GetBucketLocationRequest

Especifica os parâmetros da solicitação. Para mais informações, consulte GetBucketLocationRequest

Valores de retorno

Tipo

Descrição

GetBucketLocationResult

Valor retornado pela operação. Para mais detalhes, consulte GetBucketLocationResult

Para ver a definição completa deste método, consulte get_bucket_location.

Código de exemplo

O código a seguir mostra como consultar a região de um bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser. This script is used to obtain the location information of a specified bucket.
parser = argparse.ArgumentParser(description="Get the location of a specified OSS bucket.")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket to get the location for.', required=True)

# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')

def main():
    """
    The main function, which is used to parse command-line arguments and obtain the location information of the specified bucket.
    """

    args = parser.parse_args()  # Parse command-line arguments.

    # Load credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK, and set the credentials provider and region information.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the configured information.
    client = oss.Client(cfg)

    # Construct a request to obtain the location information of the specified bucket.
    request = oss.GetBucketLocationRequest(bucket=args.bucket)

    # Execute the request and obtain the response.
    result = client.get_bucket_location(request)

    # Print the status code, request ID, and location information of the response.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' location: {result.location}'
    )

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

Referências

  • Para obter o código de exemplo completo de consulta à região de um bucket, consulte get_bucket_location.py.