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

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

  • 实际请求所允许的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

你可能感兴趣的:(python,django,跨域)