Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie políticas de bucket usando o OSS SDK for Python 2.0

Última atualização: Sep 22, 2026

As políticas de bucket permitem autorizar ou restringir o acesso a recursos específicos do OSS para usuários anônimos ou identificados, como contas da Alibaba Cloud, usuários do RAM e funções do RAM. Por exemplo, é possível conceder permissões de somente leitura em recursos específicos do OSS a um usuário do RAM de outra conta da Alibaba Cloud.

Observações

  • Antes de configurar políticas de bucket, certifique-se de entender este recurso.

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, da região China (Hangzhou). Por padrão, o acesso a recursos em um bucket utiliza o endpoint público. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • A permissão oss:PutBucketPolicy é obrigatória para configurar uma política de bucket. Para consultar essa política, é necessária a permissão oss:GetBucketPolicy. Já para excluí-la, você precisa da permissão oss:DeleteBucketPolicy. Para mais detalhes, consulte Conceder uma política personalizada.

Métodos

Configure uma política de bucket

put_bucket_policy(request: PutBucketPolicyRequest, **kwargs) → PutBucketPolicyResult

Consulte políticas de bucket

get_bucket_policy(request: GetBucketPolicyRequest, **kwargs) → GetBucketPolicyResult

Exclua uma política de bucket

delete_bucket_policy(request: DeleteBucketPolicyRequest, **kwargs) → DeleteBucketPolicyResult

Parâmetro

Tipo

Descrição

request

PutBucketPolicyRequest

A solicitação da operação PutBucketPolicy. Para ver os parâmetros da solicitação, consulte PutBucketPolicyRequest.

GetBucketPolicyRequest

A solicitação da operação GetBucketPolicy. Para ver os parâmetros da solicitação, consulte GetBucketPolicyRequest.

DeleteBucketPolicyRequest

A solicitação da operação DeleteBucketPolicy. Para ver os parâmetros da solicitação, consulte DeleteBucketPolicyRequest.

Parâmetros de resposta

Tipo

Descrição

PutBucketPolicyResult

O valor de retorno. Para mais informações, consulte PutBucketPolicyResult.

GetBucketPolicyResult

O valor de retorno. Para detalhes, consulte GetBucketPolicyResult.

DeleteBucketPolicyResult

O valor de retorno. Para saber mais, consulte DeleteBucketPolicyResult.

Para a definição completa do método de configuração de uma política de bucket, consulte put_bucket_policy.

Para a definição completa do método de consulta de políticas de bucket, consulte get_bucket_policy.

Para a definição completa do método de exclusão de uma política de bucket, consulte delete_bucket_policy.

Código de exemplo

Configure uma política de bucket

O exemplo de código a seguir configura uma política de bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for obtaining the values of the command-line parameters.
parser = argparse.ArgumentParser(description="put bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

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 configuration of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Specify the region.
    cfg.region = args.region
    # If an endpoint is provided from the command line, update the endpoint in the configuration with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in examplebucket.
    policy_text = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Principal\": [\"20214760404935xxxx\"], \"Resource\": [\"acs:oss:*:174649585760xxxx:examplebucket/*\"]}], \"Version\": \"1\"}"

    # Apply the policy to the specified bucket.
    result = client.put_bucket_policy(oss.PutBucketPolicyRequest(
            bucket=args.bucket,
            body=policy_text,
    ))

    # Display the HTTP status code and request ID.
    print(f'status code: {result.status_code}, request id: {result.request_id}')

if __name__ == "__main__":
    main()

Consulte políticas de bucket

O exemplo de código a seguir consulta políticas de bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="get bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

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 configuration of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Specify the region.
    cfg.region = args.region
    # If an endpoint is provided from the command line, update the endpoint in the configuration with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Call get_bucket_policy to query the bucket policies.
    result = client.get_bucket_policy(oss.GetBucketPolicyRequest(
            bucket=args.bucket,
    ))

    # Display the HTTP status code, request ID, and response body.
    print(f'status code: {result.status_code},'
            f' request id: {result.request_id},'
            f' body: {result.body},'
    )

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main()

Exclua uma política de bucket

O exemplo de código a seguir exclui uma política de bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="delete bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line parameters.
    args = parser.parse_args()

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

    # Use the default configuration of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Specify the region.
    cfg.region = args.region
    # If an endpoint is provided from the command line, update the endpoint in the configuration with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Call the delete_bucket_policy method.
    result = client.delete_bucket_policy(oss.DeleteBucketPolicyRequest(
            bucket=args.bucket,  # Specify the name of the bucket to perform the operation on.
    ))

    # Display the HTTP status code and request ID.
    print(f'status code: {result.status_code}, request id: {result.request_id}')

# Execute the main function when the script is directly run.
if __name__ == "__main__":
    main()

Referências

  • Para o código de exemplo completo de configuração de uma política de bucket, acesse put_bucket_policy.py.

  • Para o código de exemplo completo de consulta de políticas de bucket, acesse get_bucket_policy.py.

  • Para o código de exemplo completo de exclusão de uma política de bucket, acesse delete_bucket_policy.py.