文章摘要
GPT 4
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结
投诉

Django,启动!!!

本篇文章用于快速配置出本人习惯的Django使用配置

settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""
Django settings for itstudio_backstage project.

Generated by 'django-admin startproject' using Django 4.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import sys
import os
import configparser

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

conf = configparser.RawConfigParser()

conf.read(os.path.join(BASE_DIR, "config.ini"), encoding="utf-8")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = conf.get("Django", "SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]

MIDDLEWARE = [
'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',
]
# todo 将###替换为项目名
ROOT_URLCONF = '###.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'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',
],
},
},
]
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
#todo 将###替换为项目名称
WSGI_APPLICATION = '###.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': conf.get("database", "ENGINE"),
'NAME': conf.get("database", "NAME"),
'USER': conf.get("database", "USER"),
'PASSWORD': conf.get("database", "PASSWORD"),
'HOST': conf.get("database", "HOST"),
'PORT': 3306,
}
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

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',
},
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

config.ini

在项目根目录下面创建config.ini

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[database]

ENGINE = django.db.backends.mysql

NAME = ouchelper

USER = dx2331lxz

PASSWORD = 1314521

HOST = localhost

[Django]

SECRET_KEY = 'django-insecure-68*wwg-r$@p72!y9exi+z+9z0lxy3am0l=1@u(6)1$je7plxqq'

下载类库

  • simpleui
1
pip install django-simpleui -i https://pypi.tuna.tsinghua.edu.cn/simple
  • rest_framework
1
pip install djangorestframework
  • mysqlclient
1
pip install mysqlclient
  • simplejwt
1
pip install djangorestframework-simplejwt

views.py

1
2
3
4
5
6
7
8
from django.shortcuts import render, HttpResponse
# from . import serializer, models
# from utils import email
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, pagination # 状态和分页
import json
import os

serializer.py

1
2
3
4
5
6
7
from rest_framework import serializers
from . import models

class Serializer(serializers.ModelSerializer):
class Meta:
# model = models.
fields = "__all__"

urls.py

1
2
3
4
5
6
7
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

jwt部分

1
2
3
4
5
6
# jwt
from rest_framework.permissions import AllowAny
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication, JWTTokenUserAuthentication
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.tokens import RefreshToken

快速jwt

  • settings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', # 使用rest_framework_simplejwt验证身份
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated' # 默认权限为验证用户
# 'rest_framework.permissions.AllowAny'
],
}

# simplejwt
SIMPLE_JWT = {
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'ROTATE_REFRESH_TOKENS': True,
}
  • urls
1
2
3
4
5
6
# 导入 simplejwt 提供的几个验证视图类
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)

跨域

1
pip install django-cors-headers

在 APP 中注册

1
2
3
4
5
6

INSTALLED_APPS = [
...,
"corsheaders",
...,
]

添加中间件

1
2
3
4
5
6
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]

配置允许通过的域名

通过配置 CORS_ALLOWED_ORIGINS 添加通过的域名

1
2
3
4
5
6
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000",
]

也可以使用正则表达式,配置 CORS_ALLOWED_ORIGIN_REGEXES,即可

1
2
3
CORS_ALLOWED_ORIGIN_REGEXES = [
r"^https://\w+\.example\.com$",
]

爱特合作的情况多半是后端部署上服务器,然后前端在本地对接后,打包代码后发给后端部署,所以需要设置一下允许内网 IP 允许跨域。

1
2
3
4
5
if DEBUG:
CORS_ALLOWED_ORIGIN_REGEXES = [
# 允许内网IP及所有端口,用于调试
r"^http://((127\.0\.0\.1)|(localhost)|(10\.\d{1,3}\.\d{1,3}\.\d{1,3})|(172\.((1[6-9])|(2\d)|(3[01]))\.\d{1,3}\.\d{1,3})|(192\.168\.\d{1,3}\.\d{1,3}))(:\d+){0,1}$",
]

注意上线之后,需要将域名 / IP + 端口 添加到白名单内

允许跨域认证
配置 CORS_ALLOW_CREDENTIALS

1
CORS_ALLOW_CREDENTIALS = True

分页

1
2
3
4
class CustomPagination(pagination.PageNumberPagination):
page_size = 10 # 每页显示的数据条数
page_size_query_param = 'page_size' # 页面数量参数名称设置
max_page_size = 100

使用实例

1
2
3
4
5
users = models.UserInfo.objects.filter(roles=3)
paginator = CustomPagination()
paginated_queryset = paginator.paginate_queryset(users, request)
serializers = serializer.RegisterSerializer(paginated_queryset, many=True)
return paginator.get_paginated_response(serializers.data)

配置图片上传

pip install Pillow

settings.py

1
2
3
4
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

根目录下面创建media、static文件夹

urls

1
2
3
4
5
6
# 导入settings
from django.conf import settings

# 导入static
from django.conf.urls.static import static

1
2
3
urlpatterns = [
`````
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)