Django项目解决跨域问题

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$",
]

以上的配置基本已经足够,如下为可选配置。django

  • 实际请求所容许的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来解决。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
相关文章
相关标签/搜索