django-cors-headers
官方文档:https://pypi.org/project/djan...
要求
- 支持Python 3.5 - 3.8
- 支持Django 1.11 - 3.0
安装
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$",]
以上的配置基本已经足够,以下为可选配置。
- 实际请求所允许的HTTP方式列表
# 默认为CORS_ALLOW_METHODS = [ 'DELETE' , 'GET' , 'OPTIONS' , 'PATCH' , 'POST' , 'PUT' ,]# 当有自定义的方式时,可使用以下配置扩展from corsheaders.defaults import default_methodsCORS_ALLOW_METHODS = list(default_methods) + [ 'POKE',]
- 实际请求时可以使用的非标准HTTP header 的列表
# 默认为CORS_ALLOW_HEADERS = [ ''accept' , 'accept-encoding' , 'authorization' , 'content-type' , 'dnt' , 'origin' , 'user-agent' , 'x-csrftoken' , 'x-requested-with' ,]# 也可自定义扩展from corsheaders.defaults import default_headersCORS_ALLOW_HEADERS = list(default_headers) + [ 'my-custom-header',]
信号的使用
场景:需要将白名单中允许的地址设置为动态可配置的,比如就是数据库中的一张表,可在后台添加或者删除可允许的地址,此时可用到corsheaders.signals
模块中的check_request_enabled
来解决。
# myapp/handlers.pyfrom corsheaders.signals import check_request_enabledfrom myapp.models import MySitedef cors_allow_mysites(sender, request, **kwargs): return MySite.objects.filter(host=request.host).exists()check_request_enabled.connect(cors_allow_mysites)
# myapp/__init__.pydefault_app_config = 'myapp.apps.MyAppConfig'
# myapp/apps.pyfrom django.apps import AppConfigclass MyAppConfig(AppConfig): name = 'myapp' def ready(self): # Makes sure all signal handlers are connected from myapp import handlers # noqa