官方文档:https://pypi.org/project/djan...数据库
pip install django-cors-headers
settings.py
文件配置INSTALLED_APPS = [ ... 'corsheaders' , ... ]
MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware' , # 注册中间件 'django.middleware.common.CommonMiddleware' , ... ]
# 容许所有来源 CORS_ORIGIN_ALLOW_ALL = True # 若是为True,将不使用白名单,而且将接受全部来源。默认为False。 # 白名单 CORS_ORIGIN_WHITELIST = [ "https://example.com", "https://sub.example.com", "http:// localhost:8080", "http://127.0.0.1:9000" ] # 白名单也可以使用正则 CORS_ORIGIN_REGEX_WHITELIST = [ r"^https://\w+\.example\.com$", ]
以上的配置基本已经足够,如下为可选配置。django
# 默认为 CORS_ALLOW_METHODS = [ 'DELETE' , 'GET' , 'OPTIONS' , 'PATCH' , 'POST' , 'PUT' , ] # 当有自定义的方式时,可以使用如下配置扩展 from corsheaders.defaults import default_methods CORS_ALLOW_METHODS = list(default_methods) + [ 'POKE', ]
# 默认为 CORS_ALLOW_HEADERS = [ ''accept' , 'accept-encoding' , 'authorization' , 'content-type' , 'dnt' , 'origin' , 'user-agent' , 'x-csrftoken' , 'x-requested-with' , ] # 也可自定义扩展 from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = list(default_headers) + [ 'my-custom-header', ]
场景:须要将白名单中容许的地址设置为动态可配置的,好比就是数据库中的一张表,可在后台添加或者删除可容许的地址,此时可用到corsheaders.signals
模块中的check_request_enabled
来解决。app
# myapp/handlers.py from corsheaders.signals import check_request_enabled from myapp.models import MySite def cors_allow_mysites(sender, request, **kwargs): return MySite.objects.filter(host=request.host).exists() check_request_enabled.connect(cors_allow_mysites)
# myapp/__init__.py default_app_config = 'myapp.apps.MyAppConfig'
# myapp/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' def ready(self): # Makes sure all signal handlers are connected from myapp import handlers # noqa