edit-icon download-icon

CORS

Last Updated: Oct 24, 2017

CORS allows web applications to access resources in other domains. OSS provides an interface for developers to control cross-origin access permissions conveniently.

For more information about CORS, see Developer Guide and API Reference.

Set CORS rules

The following code sets a CORS rule:

  1. # -*- coding: utf-8 -*-
  2. import oss2
  3. from oss2.models import BucketCors, CorsRule
  4. auth = oss2.Auth ('Your AccessKeyID', 'Your AccessKeySecret')
  5. bucket = oss2.Bucket (auth, 'Your endpoint', 'your bucket name')
  6. rule = CorsRule(allowed_origins=['*'],
  7. allowed_methods=['GET', 'HEAD'],
  8. allowed_headers=['*'],
  9. max_age_seconds=1000)
  10. bucket.put_bucket_cors(BucketCors([rule]))

Get CORS rules

  1. try:
  2. cors = bucket.get_bucket_cors()
  3. except oss2.exceptions.NoSuchCors:
  4. print('cors is not set')
  5. else:
  6. for rule in cors.rules:
  7. print('AllowedOrigins={0}'.format(rule.allowed_origins))
  8. print('AllowedMethods={0}'.format(rule.allowed_methods))
  9. print('AllowedHeaders={0}'.format(rule.allowed_headers))
  10. print('ExposeHeaders={0}'.format(rule.expose_headers))
  11. print('MaxAgeSeconds={0}'.format(rule.max_age_seconds))

Delete a CORS rule

  1. bucket.delete_bucket_cors()
Thank you! We've received your feedback.