1、安装插件
pip install django-cors-headers
2、配置 settings.py
在 settings.py 文件中,将 corsheaders 添加到 INSTALLED_APPS 列表中:
INSTALLED_APPS = [
...
'corsheaders',
...
]
3、添加到 MIDDLEWARE
将 corsheaders.middleware.CorsMiddleware 添加到 MIDDLEWARE 列表中,并确保它位于 django.middleware.common.CommonMiddleware 之前:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
4、配置 CORS 相关设置,在 settings.py 文件的末尾添加以下配置:
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
5、配置允许访问的域名白名单
如果你不想允许所有域名访问,可以通过 CORS_ALLOWED_ORIGINS 或CORS_ALLOWED_ORIGIN_REGEXES 来配置允许访问的域名白名单。
比如CORS_ALLOWED_ORIGINS=[
https://test.com,
https://sub.test.com,
https://192.168.21.121:8080,
]
6、配置文件参考
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-ws(9g7m^dty#ouzqdii*s^((+a33v@qn654gm0+b)_97)#sx-e"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"corsheaders",
"app_drf01.apps.AppDrf01Config",
"api.apps.ApiConfig",
"rest_framework_simplejwt",
"rest_framework_simplejwt.token_blacklist",
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
# "DEFAULT_THROTTLE_CLASSES": [
# "rest_framework.throttling.AnonRateThrottle", # 未认证用户
# "rest_framework.throttling.UserRateThrottle", # 已认证用户
# ],
"DEFAULT_THROTTLE_RATES": { # 频率配置
"anon": "2/min", # 匿名用户每分钟最多访问 2 次
"user": "5/min", # 认证用户每分钟最多访问 10 次
},
}
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "maker_drf.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "maker_drf.wsgi.application"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "python_demo", # 数据库名称
"USER": "root", # 数据库用户名
"PASSWORD": "1234567890", # 数据库密码
"HOST": "127.0.0.1", # 数据库主机地址
"PORT": "13306", # 数据库端口
}
}
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# 设置默认语言为中文
LANGUAGE_CODE = "zh-hans" # 简体中文
# 设置默认时区
TIME_ZONE = "Asia/Shanghai" # 上海时区
USE_I18N = True
USE_TZ = True
STATIC_URL = "static/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# 媒体文件的存储路径
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
# 媒体文件的访问 URL
MEDIA_URL = "/media/"
from datetime import timedelta
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), # Access Token 的有效期
"REFRESH_TOKEN_LIFETIME": timedelta(days=7), # Refresh Token 的有效期
"ROTATE_REFRESH_TOKENS": True, # 刷新时是否生成新的 Refresh Token
"BLACKLIST_AFTER_ROTATION": True, # 是否在刷新后废弃旧的 Refresh Token
"ALGORITHM": "HS256", # 使用的加密算法
"SIGNING_KEY": SECRET_KEY, # 设置签名密钥
"VERIFYING_KEY": None, # 如果使用公钥算法,可以配置验证密钥
}
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]