Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión de políticas de bucket con OSS SDK for Python 2.0

Última actualización: Sep 22, 2026

Las políticas de bucket permiten autorizar o restringir el acceso a recursos específicos de OSS para usuarios anónimos o identificados, como cuentas de Alibaba Cloud, usuarios de RAM y roles de RAM. Por ejemplo, puede otorgar permisos de solo lectura sobre ciertos recursos de OSS a un usuario de RAM que pertenezca a otra cuenta de Alibaba Cloud.

Notas

  • Antes de configurar bucket policies, asegúrese de comprender esta función.

  • El código de ejemplo de este tema utiliza el ID de región cn-hangzhou, correspondiente a la región China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.

  • Para configurar una política de bucket se requiere el permiso oss:PutBucketPolicy. Para consultarla, es necesario contar con el permiso oss:GetBucketPolicy. Para eliminarla, se requiere el permiso oss:DeleteBucketPolicy. Para más información, consulte Grant a custom policy.

Métodos

Configurar una política de bucket

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

Consultar políticas de bucket

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

Eliminar una política de bucket

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

Parámetro

Tipo

Descripción

request

PutBucketPolicyRequest

Solicitud para la operación PutBucketPolicy. Para conocer los parámetros de la solicitud, consulte PutBucketPolicyRequest.

GetBucketPolicyRequest

Solicitud para la operación GetBucketPolicy. Para conocer los parámetros de la solicitud, consulte GetBucketPolicyRequest.

DeleteBucketPolicyRequest

Solicitud para la operación DeleteBucketPolicy. Para conocer los parámetros de la solicitud, consulte DeleteBucketPolicyRequest.

Parámetros de respuesta

Tipo

Descripción

PutBucketPolicyResult

Valor de retorno. Para más información, consulte PutBucketPolicyResult.

GetBucketPolicyResult

Valor de retorno. Para más información, consulte GetBucketPolicyResult.

DeleteBucketPolicyResult

Valor de retorno. Para más información, consulte DeleteBucketPolicyResult.

Para consultar la definición completa del método que configura una política de bucket, visite put_bucket_policy.

La definición completa del método para consultar políticas de bucket está disponible en get_bucket_policy.

Si necesita la definición completa del método que elimina una política de bucket, revise delete_bucket_policy.

Código de ejemplo

Configurar una política de bucket

A continuación se muestra un ejemplo de código para configurar una 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

El siguiente fragmento de código ilustra cómo consultar 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()

Eliminar una política de bucket

Este último ejemplo muestra cómo eliminar una 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()

Referencias

  • Para ver el código de ejemplo completo que configura una política de bucket, visite put_bucket_policy.py.

  • El código de ejemplo completo para consultar políticas de bucket se encuentra en get_bucket_policy.py.

  • Si necesita el código de ejemplo completo para eliminar una política de bucket, acceda a delete_bucket_policy.py.