Todos os produtos
Search
Central de documentação

Object Storage Service:Ativar o modo de pagamento pelo solicitante com o OSS SDK for Python 2.0

Última atualização: Jul 03, 2026

O modo de pagamento pelo solicitante é compatível. Quando ativado para um bucket, o solicitante paga as taxas de requisição e tráfego, e o proprietário do bucket arca apenas com os custos de armazenamento. Você pode ativar esse modo para compartilhar dados sem custear as taxas de requisição e tráfego geradas pelos acessos ao bucket.

Observações de uso

  • Os exemplos de código deste tópico usam o ID da região cn-hangzhou, referente à região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre via endpoint público. Para acessar esses recursos a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.

  • Para definir o modo de pagamento pelo solicitante, você precisa da permissão oss:PutBucketRequestPayment. Para consultar a configuração desse modo, é necessária a permissão oss:GetBucketRequestPayment. Para saber mais, consulte Conceder permissões personalizadas a um usuário RAM.

Exemplos de código

Ativar o pagamento pelo solicitante para um bucket

O exemplo de código a seguir mostra como ativar o pagamento pelo 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.

Consultar configurações de pagamento pelo solicitante

O exemplo de código a seguir mostra como consultar as configurações de pagamento pelo solicitante de um 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.

Referências