All Products
Search
Document Center

Object Storage Service:Cross-origin resource sharing (Python SDK V2)

Last Updated:Aug 01, 2025

Because of the same-origin policy in browsers, cross-origin requests may be rejected when data is exchanged or resources are shared between different domain names. This topic describes how to configure cross-origin resource sharing (CORS) rules. In the CORS rules, you can specify the allowed origin domain names, request methods, and headers.

Notes

  • The sample code in this topic uses the region ID cn-hangzhou for the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see OSS regions and endpoints.

  • To configure CORS rules, you must have the oss:PutBucketCors permission. To query CORS rules, you must have the oss:GetBucketCors permission. To delete CORS rules, you must have the oss:DeleteBucketCors permission. For more information, see Grant custom policy to RAM users.

Method definition

Configure CORS rules

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

Query CORS rules

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

Delete CORS rules

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

Request parameters

Parameter

Type

Description

request

PutBucketCorsRequest

The request parameter. For more information, see PutBucketCorsRequest

GetBucketCorsRequest

The request parameter. For more information, see GetBucketCorsRequest

DeleteBucketCorsRequest

The request parameter. For more information, see DeleteBucketCorsRequest

Response parameters

Type

Description

PutBucketCorsResult

The return value. For more information, see PutBucketCorsResult

GetBucketCorsResult

The return value. For more information, see GetBucketCorsResult

DeleteBucketCorsResult

The return value. For more information, see DeleteBucketCorsResult

For more information about configuring CORS rules, see put_bucket_cors.

For more information about querying CORS rules, see get_bucket_cors.

For more information about deleting CORS rules, see delete_bucket_cors.

Sample code

Configure CORS rules

You can use the following code to configure CORS rules for a specific bucket.

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.

Query CORS rules

You can use the following code to query CORS rules.

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.

Delete CORS rules

You can use the following code to delete all CORS rules of a specific bucket.

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.

References