当前位置: 首页 > news >正文

Django服务开发镜像构建

最后完整的项目目录结构

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;}}
}

http://www.lryc.cn/news/579098.html

相关文章:

  • C++主流编辑器特点比较
  • Java 并发编程的 CAS(Compare and Swap)是什么?
  • 讲解“/etc/ssh/sshd_config “的“HostKey /etc/ssh/ssh_host_ed25519_key“ 笔记250702
  • pdf删除一页 python实现(已验证)
  • 模板编译原理
  • 使用OpenCV识别图片相似度评分的应用
  • YOLOv11剪枝与量化(一)模型压缩的必要性
  • 深入理解C++11原子操作:从内存模型到无锁编程
  • SpringCloud系列(47)--SpringCloud Bus实现动态刷新定点通知
  • 04-动态规划
  • 数学建模_微分方程
  • 内存架构的十字路口:深入解析统一内存访问(UMA)与非一致内存访问(NUMA)
  • 虚拟机知识点-Vagrant 在通过 VirtualBox 启动 CentOS 虚拟机时失败-VERR_NEM_VM_CREATE_FAILED
  • 从0开始学习R语言--Day36--空间杜宾模型
  • maven仓库
  • WSL2 + Docker Desktop 环境中查看本地镜像
  • 【Vue入门学习笔记】Vue核心语法
  • CentOS 卸载docker
  • 移动conda虚拟环境的安装目录
  • mongo常用命令
  • odoo17 警示: selection attribute will be ignored as the field is related
  • Node.js-http模块
  • Day04:玩转标准库中的数据处理与日志记录
  • Chart.js 安装使用教程
  • 基于SpringBoot和Leaflet的区域冲突可视化系统(2025企业级实战方案)
  • VC Spyglass:工具简介
  • React Native 开发环境搭建--window--android
  • 24年京东秋季笔试题
  • CSS外边距合并(塌陷)全解析:原理、场景与解决方案
  • flutter更改第三方库pub get的缓存目录;更改.gradle文件夹存放目录