共计 1659 个字符,预计需要花费 5 分钟才能阅读完成。
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_methods | |
CORS_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_headers | |
CORS_ALLOW_HEADERS = list(default_headers) + ['my-custom-header',] |
信号的使用
场景:需要将白名单中允许的地址设置为动态可配置的,比如就是数据库中的一张表,可在后台添加或者删除可允许的地址,此时可用到 corsheaders.signals
模块中的 check_request_enabled
来解决。
# 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 |
正文完