最后完整的項目目錄結構
1、安裝依賴
pip install django django-tables2 django-filter
2、創建項目和主應用
django-admin startproject config
cd config
python manage.py startapp dynamic_models
3、配置settings.py
將項目模塊dynamic_models加入進來,django_tables2和django_filters是安裝的原生的依賴,使用里面的自帶的界面,
1)注意這里面的ALLOWED_HOSTS 和 CSRF_TRUSTED_ORIGINS需要配置成對應的可信的網站和地址
2)STATIC_ROOT必須與 Dockerfile 中一致
其余的配置如數據庫按需配置即可.
"""
Django settings for config project.Generated by 'django-admin startproject' using Django 5.2.3.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-1$72i_+zz_bh8l$n5og-6-))(4vw3%!*m7!hi#^7l11g!3@tdn"# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = TrueALLOWED_HOSTS = ['zs-common-config-dev.com','zs-common-config-pre.com','zs-common-config.com','10.1.1.1','*',
]CSRF_TRUSTED_ORIGINS = ['zs-common-config-dev.com','zs-common-config-pre.com','zs-common-config.com','10.1.1.1','*',
]# 必須配置(如果使用HTTPS)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = True # HTTPS必須為True
SESSION_COOKIE_SECURE = True# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','dynamic_models','django_tables2','django_filters',
]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",
]ROOT_URLCONF = "config.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','django.template.context_processors.request', # 用于django-tables2],},},
]WSGI_APPLICATION = "config.wsgi.application"# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databasesDATABASES = {"default": {# "ENGINE": "django.db.backends.sqlite3",# "NAME": BASE_DIR / "db.sqlite3",'ENGINE': 'django.db.backends.postgresql','NAME': 'zskj_common_config_dev', # 數據庫名稱'USER': 'postgres', # 數據庫用戶名'PASSWORD': '123456', # 數據庫密碼'HOST': 'localhost', # 數據庫主機,本地數據庫使用 localhost'PORT': '123456', # 數據庫端口,PostgreSQL 默認是 5432}
}# 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 = "en-us"
LANGUAGE_CODE = 'zh-hans' # 簡體中文
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/# 靜態文件 URL 前綴(瀏覽器訪問路徑)
STATIC_URL = '/static/'STATIC_ROOT = '/app/staticfiles/' # 必須與 Dockerfile 中一致
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # 開發靜態文件目錄# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-fieldDEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
4、實現模塊dynamic_models的功能,添加路由
以上是該模塊提供出來的路由。
需要將模塊的url添加到主服務config的urls里面
以上第二個path,代表不輸入具體的路由地址,則自動跳轉到admin路由下
5、生成數據庫表
python manage.py migrate
6、創建超級用戶,用于登錄
python manage.py createsuperuser
7、創建虛擬環境(本地啟動需要,服務端忽略)
python3 -m venv myenv
source myenv/bin/activate # 適用于 Linux/MacOS
.\myenv\Scripts\activate # 適用于 Windows
8、models有修改,更新
python manage.py makemigrations dynamic_models
python manage.py migrate
9、requirements.txt依賴
pip install -r requirements.txt
asgiref==3.8.1
Django==5.2.3
django-filter==25.1
django-tables2==2.7.5
psycopg2-binary==2.9.10
sqlparse==0.5.3
gunicorn==23.0.0
10、本地啟動
如圖配置,pycharm
11、構建docker鏡像
# 基礎鏡像
FROM harbor-operation.maas.com.cn/zskj/backend/python-poetry:3.10ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV DJANGO_SETTINGS_MODULE=config.settings# 創建工作目錄并設置為工作目錄
WORKDIR /app# 復制項目文件
COPY . /app/# 安裝Python依賴
RUN pip install --upgrade pip
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
RUN pip install -r requirements.txt# 收集靜態文件到 STATIC_ROOT
RUN python manage.py collectstatic --noinputEXPOSE 8000CMD ["gunicorn", "--bind", "0.0.0.0:8000", "config.wsgi:application"]# docker build -t harbor-operation.maas.com.cn/zskj/backend/zskj_common_config:v1.0.6 .
# docker run -p 8002:8000 --name zskj-app6 harbor-operation.maas.com.cn/zskj/backend/zskj_common_config:v1.0.6
12、docker-compose
name: "common-config-dev"
services:api:container_name: common_config_devrestart: alwaysimage: common_config:v1.0.9command: >sh -c "python manage.py collectstatic --noinput &&gunicorn --bind 0.0.0.0:8000 config.wsgi:application"volumes:- ./static/:/app/staticfiles/ports:- "8059:8000"networks:- docker_common_config_network_devenvironment:- START_CONFIG=dev- DJANGO_SETTINGS_MODULE=config.settings- DEBUG=Truenginx:container_name: common_config_nginx_devimage: common_config_nginx:v1.0.1ports:- "51149:80"networks:- docker_common_config_network_devvolumes:- ./static/:/app/staticfiles/- ./nginx/nginx.conf:/etc/nginx/conf.d/default.confdepends_on:- apinetworks:docker_common_config_network_dev:ipam:config:- subnet: 172.70.49.16/28driver: bridge
注意需要把服務端的容器內部的資源掛載出來,不然訪問時找不到對應的資源
./static/:/app/staticfiles/
13、nginx的配置
dockerfile
FROM nginx:latest
# 設置時區為中國標準時間
ENV TZ=Asia/Shanghai
# 配置NGINX
COPY nginx.conf /etc/nginx/nginx.conf
# 暴露端口
EXPOSE 80
# 啟動NGINX
CMD ["nginx", "-g", "daemon off;"]
# 構建鏡像
# docker build -t common_config_nginx:v1.0.1 .
?nginx.conf
events {worker_connections 1024;
}http {#設定請求緩沖client_header_buffer_size 512k;large_client_header_buffers 4 512k;# 解決樣式不加載問題include /etc/nginx/mime.types;default_type application/octet-stream;upstream zskj_common_config_interface {# 這里的端口是容器里面的端口server api:8000;}server {listen 80;location /static/ {alias /app/staticfiles/;expires 30d;access_log off;# 解決樣式不加載問題add_header Content-Type text/css;types {}default_type text/css;}location / {# 設置ipproxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;# 解決跨域add_header 'Access-Control-Allow-Origin' '$http_origin' always;add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;# 注意前端如果傳了其他的請求頭,會跨域的哦,例如Refresh-Token不在下面的字符串中,會提示跨域add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;# 處理OPTIONS預檢請求if ($request_method = 'OPTIONS') {return 204;}proxy_pass http://zskj_common_config_interface;}}
}