Tous les produits
Search
Centre de documentation

Object Storage Service:Activer le mode de paiement par requérant à l'aide du SDK OSS pour Python 2.0

Dernière mise à jour :Aug 18, 2026

Le mode de paiement par requérant est pris en charge. Lorsqu'il est activé pour un bucket, le requérant assume les frais de requête et de trafic, tandis que le propriétaire du bucket prend en charge les coûts de stockage. Activez cette option pour partager les données de votre bucket sans supporter les frais liés aux requêtes et au trafic lors des accès externes.

Notes d'utilisation

  • Les exemples de code de cette rubrique utilisent l'ID de région cn-hangzhou correspondant à la région Chine (Hangzhou). Par défaut, un endpoint public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez y accéder depuis d'autres services Alibaba Cloud situés dans la même région, privilégiez un endpoint interne. Pour plus d'informations sur les régions et endpoints pris en charge par OSS, consultez la rubrique Régions et endpoints.

  • Pour configurer le mode de paiement par requérant, vous devez disposer de l'autorisation oss:PutBucketRequestPayment. Pour récupérer la configuration de ce mode, l'autorisation oss:GetBucketRequestPayment est requise. Pour en savoir plus, reportez-vous à la section Accorder des autorisations personnalisées à un utilisateur RAM.

Exemples de code

Activer le paiement par requérant pour un bucket

L'exemple de code suivant illustre la procédure d'activation du paiement par requérant :

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.

Interroger les configurations de paiement par requérant

Le code ci-dessous montre comment récupérer les configurations de paiement par requérant d'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.

Références