Todos los productos
Search
Centro de documentos

Object Storage Service:Habilite el modo de pago por solicitante con OSS SDK para Python 2.0

Última actualización: Sep 03, 2026

El modo de pago por solicitante es compatible con Object Storage Service (OSS). Cuando este modo se habilita en un bucket, quien realiza la solicitud asume los costos de tráfico y de peticiones, mientras que el propietario del bucket cubre únicamente los gastos de almacenamiento. Esta función permite compartir datos sin incurrir en cargos por solicitudes ni tráfico cuando terceros acceden al contenido.

Notas de uso

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

  • Para configurar el modo de pago por solicitante, debe contar con el permiso oss:PutBucketRequestPayment. Para consultar la configuración actual de este modo, requiere el permiso oss:GetBucketRequestPayment. Para más detalles, consulte Grant custom permissions to a RAM user.

Código de ejemplo

Habilite el pago por solicitante en un bucket

A continuación se muestra un ejemplo de código para habilitar el modo de pago por solicitante:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: set the request payment configuration for a bucket.
parser = argparse.ArgumentParser(description="put bucket request payment sample")

# Define command-line arguments, including the required region, bucket name, optional endpoint, and payer.
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')
parser.add_argument('--payer', help='Indicates who pays the download and request fees. Possible values: "Requester" or "BucketOwner"', required=True)

def main():
    # Parse command-line arguments to obtain user-input values.
    args = parser.parse_args()

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

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Send a request to set the request payment configuration for the specified bucket.
    result = client.put_bucket_request_payment(oss.PutBucketRequestPaymentRequest(
            bucket=args.bucket,  # The bucket name.
            request_payment_configuration=oss.RequestPaymentConfiguration(
                payer=args.payer,  # The payer. Valid values: "Requester" or "BucketOwner".
            ),
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Consulte la configuración de pago por solicitante

El siguiente fragmento ilustra cómo obtener la configuración de pago por solicitante de un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: obtain the request payment configuration for a bucket.
parser = argparse.ArgumentParser(description="get bucket request payment sample")

# Define command-line arguments, including the required region, bucket name, and optional endpoint.
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 arguments to obtain user-input values.
    args = parser.parse_args()

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

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Send a request to obtain the request payment configuration for the specified bucket.
    result = client.get_bucket_request_payment(oss.GetBucketRequestPaymentRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code, request ID, and payer information of the operation result to confirm the request status and configuration details.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' payer: {getattr(result.request_payment_configuration, "payer", "Not set")},'
          )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Referencias

  • Para consultar el código de ejemplo completo utilizado para configurar el modo de pago por solicitante, revise put_bucket_request_payment.py.

  • Para ver el código de ejemplo completo que permite obtener la configuración del modo de pago por solicitante, consulte get_bucket_request_payment.py.