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;
        }
    }
}
相关推荐
菜鸟~noob2331 天前
[AI]间章:系列走到这里,聊聊后面的规划、造卡需要的软件平台,以及为什么我要先暂停更新
人工智能·python·fpga开发·django·pygame
prince_zxill1 天前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751
一条大祥脚3 天前
Agent Memory 全解析:从 SQLite、向量库 + RAG 到 Zep、Mem0
sqlite·agent·rag·智能体记忆
承渊政道4 天前
【Python编程—从入门到实践】(用户账户:给Django网站装上登录系统,让每个人拥有自己的学习笔记)
python·学习·pycharm·django
承渊政道4 天前
【Python编程—从入门到实践】(设置样式并部署:给Django网站换新装,把学习笔记发布到互联网)
python·学习·pycharm·django
wuyk5555 天前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
2601_967979125 天前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt
FYKJ_20105 天前
springboot同人周边订单管理系统48955-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·django·php·课程设计
2601_967979126 天前
纯手写:Python安装pip完整教程,搞了几小时,终于成功
python·教程·pip·安装·包管理
yuyuxun16 天前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计