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 = True

ALLOWED_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 definition

INSTALLED_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/#databases

DATABASES = {
    "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-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/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-field

DEFAULT_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.10

ENV 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 --noinput

EXPOSE 8000

CMD ["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_dev
    restart: always
    image: common_config:v1.0.9
    command: >
        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_dev
    environment:
      - START_CONFIG=dev
      - DJANGO_SETTINGS_MODULE=config.settings
      - DEBUG=True

  nginx:
    container_name: common_config_nginx_dev
    image: common_config_nginx:v1.0.1
    ports:
      - "51149:80"
    networks:
      - docker_common_config_network_dev
    volumes:
      - ./static/:/app/staticfiles/
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - api

networks:
  docker_common_config_network_dev:
    ipam:
      config:
        - subnet: 172.70.49.16/28
    driver: 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 / {
            # 设置ip
            proxy_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;
        }
    }
}
相关推荐
华子w90892585910 小时前
基于 Python Django 和 Spark 的电力能耗数据分析系统设计与实现7000字论文实现
python·spark·django
liulun15 小时前
在浏览器中使用SQLite(官方sqlite3.wasm)
数据库·sqlite·wasm
博观而约取1 天前
Django 数据迁移全解析:makemigrations & migrate 常见错误与解决方案
后端·python·django
哈里谢顿2 天前
Django REST Framework 中序列化器的Meta详解
django
旷世奇才李先生2 天前
SQLite 安装使用教程
数据库·sqlite
EasyCVR2 天前
SQLite不够用?视频汇聚系统EasyCVR切换MySQL数据库的关键参数怎么调?
数据库·mysql·sqlite
GDAL2 天前
Node.js v22.5+ 官方 SQLite 模块全解析:从入门到实战
数据库·sqlite·node.js
博观而约取2 天前
Django ORM 1. 创建模型(Model)
数据库·python·django
像风一样自由20202 天前
SQLite与MySQL:嵌入式与客户端-服务器数据库的权衡
数据库·mysql·sqlite