Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 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 Alibaba Cloud, usuários RAM e funções RAM. Por exemplo, você pode conceder permissões de somente leitura sobre recursos específicos do OSS a um usuário RAM de outra conta Alibaba Cloud.

Observações

  • Antes de configurar as políticas de bucket, certifique-se de compreender esse recurso.

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o endpoint público acessa os recursos em um bucket. Para acessar os recursos do 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.

  • Configure uma política de bucket com a permissão oss:PutBucketPolicy. Consulte uma política de bucket com a permissão oss:GetBucketPolicy. Exclua uma política de bucket com a 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

Consultar 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

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

GetBucketPolicyRequest

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

DeleteBucketPolicyRequest

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

Parâmetros de resposta

Tipo

Descrição

PutBucketPolicyResult

Valor retornado. Para mais informações, consulte PutBucketPolicyResult.

GetBucketPolicyResult

Valor retornado. Para mais informações, consulte GetBucketPolicyResult.

DeleteBucketPolicyResult

Valor retornado. Para mais informações, consulte DeleteBucketPolicyResult.

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

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

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

Código de exemplo

Configure uma política de bucket

O exemplo 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()

Consultar políticas de bucket

O exemplo 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 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 obter o código de exemplo completo de configuração de política de bucket, acesse put_bucket_policy.py.

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

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