注意:如果是使用?PyCharm 編程工具就不用創建虛擬化,直接打開?PyCharm 選擇新建的目錄
直接調過下面的步驟1
1. 項目初始化
如果不是用?PyCharm 編輯器就需要手動創建虛擬環境
在項目目錄cmd,自定義名稱的虛擬環境
# 激活虛擬環境
python -m venv django_env
# 激活虛擬環境
django_env\Scripts\activate.bat # Windows
# source django_env/bin/activate # Linux/Mac
# 驗證虛擬環境是否激活(提示符前應顯示 (django_env))
(django_env) F:\git\project\serverAdmin\Django>
2. 安裝依賴
# 安裝 Django 及必要組件
pip install django django-cors-headers djangorestframework django-redis redis djangorestframework-simplejwt mysqlclient
如果提示升級pip,是新項目建議更新?
# 驗證安裝版本
python -m django --version # 應顯示 Django 版本號
3. 創建項目與多應用結構
# 創建 Django 項目
django-admin startproject backend
# 進入項目目錄
cd backend
# 創建多個應用,自行創建
python manage.py startapp accounts # 用戶認證
python manage.py startapp products # 商品管理
python manage.py startapp orders # 訂單系統
python manage.py startapp utils # 工具類
4. 核心配置(backend/settings.py
)
"""
Django settings for backend project.Generated by 'django-admin startproject' using Django 5.2.4.For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
import os
from pathlib import Path# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-e6)+pcowg#7$$t=mfje93!%186-qa6=8f5$i86l8gjpyl&yukx"# SECURITY WARNING: don't run with debug turned on in production! 生產環境中禁用調試模式
DEBUG = True # 開發環境
# DEBUG = False # 生產環境ALLOWED_HOSTS = ['*'] # 開發環境
# ALLOWED_HOSTS = ['api.your-domain.com'] # 生產環境# Application definition 應用注冊
INSTALLED_APPS = ["django.contrib.admin","django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles",'corsheaders', # 跨域支持'rest_framework', # REST API'django_redis', # Redis緩存'accounts', # 權限'utils', # 工具應用
]# 中間件
MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', # 跨域必須在CommonMiddleware之前"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",
]# 跨域配置(開發環境)
CORS_ALLOW_ALL_ORIGINS = True # 允許所有域名跨域(開發環境)
# 生產環境使用白名單:
# CORS_ALLOWED_ORIGINS = [
# "http://localhost:3000", # 前端開發服務器
# "https://your-frontend.com", # 生產環境域名
# ]# 允許攜帶憑證(如cookies、HTTP認證)
CORS_ALLOW_CREDENTIALS = True # 允許跨域請求攜帶憑證
# 允許的請求方法
CORS_ALLOW_METHODS = ['DELETE','GET','OPTIONS','PATCH','POST','PUT',
]
# 允許的請求頭
CORS_ALLOW_HEADERS = ['accept','accept-encoding','authorization', # 用于JWT認證'content-type','dnt','origin','user-agent','x-csrftoken','x-requested-with','token', # 自定義token頭'openid', # 自定義openid頭'sessionkey', # 自定義session頭
]# DRF 配置
REST_FRAMEWORK = {# ... 已有配置 ...'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication', # 示例:JWT認證'rest_framework.authentication.SessionAuthentication', # 會話認證],'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated', # 默認需要登錄]
}# Redis 配置
CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379/0", # Redis 服務器地址和數據庫編號"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient","CONNECTION_POOL_KWARGS": {"max_connections": 100}, # 連接池最大連接數"PASSWORD": "", # 如果 Redis 有密碼,添加到這里}}
}
# Session 存儲(可選:使用 Redis 存儲會話)
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
ROOT_URLCONF = "backend.urls"# 數據庫配置(示例:MySQL)
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'your_database','USER': 'root','PASSWORD': 'your_password','HOST': 'localhost','PORT': '3306',}
}TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates","DIRS": [],"APP_DIRS": True,"OPTIONS": {"context_processors": ["django.template.context_processors.request","django.contrib.auth.context_processors.auth","django.contrib.messages.context_processors.messages",],},},
]WSGI_APPLICATION = "backend.wsgi.application"# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases# DATABASES = {
# "default": {
# "ENGINE": "django.db.backends.sqlite3",
# "NAME": BASE_DIR / "db.sqlite3",
# }
# }# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validatorsAUTH_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/5.2/topics/i18n/
# 改中國
LANGUAGE_CODE = "zh-hans"
TIME_ZONE = 'Asia/Shanghai'
# 確保默認字符編碼是 UTF-8
DEFAULT_CHARSET = 'utf-8'USE_I18N = True
USE_L10N = True
USE_TZ = True# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/# 生產 靜態文件配置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')# STATICFILES_DIRS = [BASE_DIR / 'static'] # 開發 時靜態文件存放路徑# 媒體文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-fieldDEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
5.項目級路由(backend/urls.py
)
"""
URL configuration for backend project.The `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""from django.contrib import admin
from django.urls import path, include
from .Index import loginurlpatterns = [path("admin/", admin.site.urls),# 公共路由path('index/login/', Index.login), # 用戶登錄# 所有API路由統一入口path('api/utils/', include('utils.urls')), # 工具類應用
]
在公共目錄,創建需要登錄API的 Index 文件 login方法
比如 path('index/login/', Index.login), # 用戶登錄
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods# 登錄后臺
@require_http_methods(["GET", "POST"])
def login(request):print(666)data = {"code": 2000,"date": [],"message": "登錄驗證"}return JsonResponse(data)
其它子應用路由?分發
比如? path('api/utils/', include('utils.urls')), ?# 工具類應用
在utils創建路由文件
from django.urls import path
from .index import Indexurlpatterns = [path('index/', Index.index)
]
創建子應用的文件和方法? path('index/', Index.index)?
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods@require_http_methods(["GET", "POST"])
def index(request):print(666)data = {"code": 2000,"date": [],"message": "我是子應用"}return JsonResponse(data)
?這樣就是多應用的前后分離了,也可以在nginx那做負載均衡
6.運行項目
# 遷移數據庫
python manage.py makemigrations
python manage.py migrate# 創建超級用戶
python manage.py createsuperuser# 啟動開發服務器
python manage.py runserver
# 指定端口
python manage.py runserver 8100
訪問地址:
公告API接口
http://127.0.0.1:8100/index/login/ 子應用
http://127.0.0.1:8100/api/utils/index/
如果像要psot請求要攜帶 CSRF 令牌
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
# 生成CSRF 令牌
from django.middleware.csrf import get_token# 登錄后臺
@require_http_methods(["GET", "POST"])
def login(request):print(6666)token = get_token(request)data = {"code": 2000,"date": [],'csrf_token': token,"message": "查詢成功"}return JsonResponse(data)
?前端必須帶??X-CSRFToken 頭,必須是這個名X-CSRFToken
// 1. 獲取 CSRF 令牌
axios.get('/api/csrf/').then(response => {const csrfToken = response.data.csrf_token;// 2. 發送 POST 請求時,在請求頭中攜帶令牌axios.post('/api/utils/index/', {}, {headers: {'X-CSRFToken': csrfToken // 關鍵:必須用 X-CSRFToken 頭}}).then(res => console.log(res.data)).catch(err => console.error(err));});
或者settings.py文件注釋django.middleware.csrf.CsrfViewMiddleware,關閉CSRF防護
# 中間件
MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', # 跨域必須在CommonMiddleware之前"django.middleware.security.SecurityMiddleware","django.contrib.sessions.middleware.SessionMiddleware","django.middleware.common.CommonMiddleware",# "django.middleware.csrf.CsrfViewMiddleware", # 關閉 CSRF 防護 前端不用攜帶 CSRF 令牌 可以post訪問"django.contrib.auth.middleware.AuthenticationMiddleware","django.contrib.messages.middleware.MessageMiddleware","django.middleware.clickjacking.XFrameOptionsMiddleware",
]