Django,启动!!!

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

settings.py

"""
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

[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
pip install django-simpleui -i https://pypi.tuna.tsinghua.edu.cn/simple
  • rest_framework
pip install djangorestframework
  • mysqlclient
pip install mysqlclient
  • simplejwt
pip install djangorestframework-simplejwt

views.py

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

from rest_framework import serializers
from . import models

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

urls.py

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部分

# 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
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
# 导入 simplejwt 提供的几个验证视图类
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)

跨域

pip install django-cors-headers

在 APP 中注册


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

添加中间件

MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]

配置允许通过的域名

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

CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000",
]

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

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

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

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

CORS_ALLOW_CREDENTIALS = True

分页

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

使用实例

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

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

# 导入settings
from django.conf import settings

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

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