Tous les produits
Search
Centre de documentation

Object Storage Service:Partage de ressources cross-origin (SDK Python V2)

Dernière mise à jour :Aug 18, 2026

Les navigateurs appliquent la politique de même origine et peuvent rejeter les requêtes cross-origin entre différents noms de domaine. Configurez des règles de partage de ressources cross-origin (CORS) pour spécifier les origines, les méthodes de requête et les en-têtes autorisés.

Notes

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou pour la région Chine (Hangzhou). Par défaut, un endpoint public permet d'accéder aux ressources d'un bucket. Pour accéder aux ressources du bucket depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints pris en charge par OSS, consultez Régions et endpoints OSS.

  • Pour configurer des règles CORS, vous devez disposer de l'autorisation oss:PutBucketCors. Pour interroger les règles CORS, vous devez disposer de l'autorisation oss:GetBucketCors. Pour supprimer des règles CORS, vous devez disposer de l'autorisation oss:DeleteBucketCors. Pour plus d'informations, consultez Accorder une politique personnalisée aux utilisateurs RAM.

Définition de la méthode

Configurer des règles CORS

put_bucket_cors(request: PutBucketCorsRequest, **kwargs) → PutBucketCorsResult

Interroger des règles CORS

get_bucket_cors(request: GetBucketCorsRequest, **kwargs) → GetBucketCorsResult

Supprimer des règles CORS

delete_bucket_cors(request: DeleteBucketCorsRequest, **kwargs) → DeleteBucketCorsResult

Paramètres de requête

Paramètre

Type

Description

request

PutBucketCorsRequest

Le paramètre de requête. Pour plus d'informations, consultez PutBucketCorsRequest

GetBucketCorsRequest

Le paramètre de requête. Pour plus d'informations, consultez GetBucketCorsRequest

DeleteBucketCorsRequest

Le paramètre de requête. Pour plus d'informations, consultez DeleteBucketCorsRequest

Paramètres de réponse

Type

Description

PutBucketCorsResult

La valeur de retour. Pour plus d'informations, consultez PutBucketCorsResult

GetBucketCorsResult

La valeur de retour. Pour plus d'informations, consultez GetBucketCorsResult

DeleteBucketCorsResult

La valeur de retour. Pour plus d'informations, consultez DeleteBucketCorsResult

Pour plus d'informations sur la configuration des règles CORS, consultez put_bucket_cors.

Pour plus d'informations sur l'interrogation des règles CORS, consultez get_bucket_cors.

Pour plus d'informations sur la suppression des règles CORS, consultez delete_bucket_cors.

Exemple de code

Configurer des règles CORS

Le code suivant configure des règles CORS pour un bucket spécifique.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Configure CORS for a bucket.
parser = argparse.ArgumentParser(description="put bucket cors sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint and response_vary.
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('--response_vary', help='Indicates whether the Vary: Origin header was returned. Default value: false', default='false')

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

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

    # Use the default configurations of the SDK to create a configuration object 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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to configure CORS for the specified bucket.
    result = client.put_bucket_cors(oss.PutBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
            cors_configuration=oss.CORSConfiguration(
                cors_rules=[
                    # The first CORS rule.
                    oss.CORSRule(
                        allowed_origins=['*'],  # Allow all origins.
                        allowed_methods=['GET', 'HEAD'],  # The allowed methods.
                        allowed_headers=['GET'],  # The allowed request headers.
                        expose_headers=['x-oss-test', 'x-oss-test1'],  # The exposed response headers.
                        max_age_seconds=33012,  # The validity period of the preflight request.
                    ),
                    # The second CORS rule.
                    oss.CORSRule(
                        allowed_origins=['http://www.example.com'],  # Allow specific origins.
                        allowed_methods=['PUT', 'POST'],  # The allowed methods.
                        allowed_headers=['*'],  # Allow all request headers.
                        expose_headers=['x-oss-test2', 'x-oss-test3'],  # The exposed response headers.
                        max_age_seconds=33012,  # The validity period of the preflight request.
                    )
                ],
                response_vary=args.response_vary,  # Specifies whether to return the Vary: Origin header. The default value is False.
            ),
    ))

    # 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 the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts here.

Interroger des règles CORS

Le code suivant interroge les règles CORS configurées pour un bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Query the CORS configuration of a bucket.
parser = argparse.ArgumentParser(description="get bucket cors sample")

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

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

    # Use the default configurations of the SDK to create a configuration object 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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to query the CORS configuration of the specified bucket.
    result = client.get_bucket_cors(oss.GetBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code, request ID, and response vary value of the operation result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' response vary: {result.cors_configuration.response_vary},'
          )

    # Traverse and print the details of each CORS rule.
    for r in result.cors_configuration.cors_rules:
        print(f'result: {r.max_age_seconds}, {r.allowed_origins}, {r.allowed_methods}, {r.allowed_headers}, {r.expose_headers}')

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

Supprimer des règles CORS

Le code suivant supprime toutes les règles CORS d'un bucket spécifique.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Delete the CORS configuration of a bucket.
parser = argparse.ArgumentParser(description="delete bucket cors sample")

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

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

    # Use the default configurations of the SDK to create a configuration object 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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to delete the CORS configuration of the specified bucket.
    result = client.delete_bucket_cors(oss.DeleteBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # 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 the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts here.

Références

  • Pour plus d'informations sur la résolution des erreurs courantes de configuration CORS, consultez 34-CORS.

  • Pour obtenir l'exemple de code complet permettant de configurer des règles CORS, consultez put_bucket_cors.py.

  • Pour obtenir l'exemple de code complet permettant d'interroger des règles CORS, consultez get_bucket_cors.py.

  • Pour obtenir l'exemple de code complet permettant de supprimer des règles CORS, consultez delete_bucket_cors.py.