22.django

发表于 未分类 分类,标签:
------------------------------------------------
python3 --version
# 应为 Python 3.10+ 或 3.12

sudo apt update
sudo apt install python3 python3-pip python3-venv -y

mkdir ~/my_django_project
cd ~/my_django_project
python3 -m venv name
source venv/bin/activate

pip install "Django==5.0.6" -i https://mirrors.aliyun.com/pypi/simple/
python -m django --version



django-admin startproject myproject
python manage.py startapp myapp
python manage.py startapp myapp --database=qunr_api

python manage.py makemigrations qunr_user
python manage.py migrate

python manage.py migrate
python manage.py runserver 0.0.0.0:8000


------------------------------------------------
vim requirements.txt
Django==5.0.6           # LTS,稳定版本
gunicorn              # 用于生产环境部署
psycopg2-binary       # PostgreSQL 支持
mysqlclient           # MySQL 支持(推荐比 pymysql 稳定)
pymysql               # 可选的纯 Python MySQL 驱动
djangorestframework   # Django REST API 支持


------------------------------------------------
vim dockerfile
# 使用你指定的基础镜像
FROM registry.cn-hangzhou.aliyuncs.com/leiuvn/python:3.12

# 设置工作目录
WORKDIR /app

# 复制依赖文件并安装依赖
COPY requirements.txt .

RUN pip install --upgrade pip && pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/

# 复制所有项目代码
COPY . .

# 暴露端口(Gunicorn 默认使用 8000)
EXPOSE 8000

# 默认启动命令(开发可改为 python manage.py runserver 0.0.0.0:8000)
CMD ["gunicorn", "projectname.wsgi:application", "--bind", "0.0.0.0:8000"]


------------------------------------------------
vim lbu_api
重点:下面数据库配置完再运行
services:
  django:
    build: .
    container_name: lbu_api
    ports:
      - "8000:8000"  # 绑定宿主机端口到容器端口
    volumes:
      - /data/wwwroot/lbu_api:/app
    networks:
      lbu_net:
        ipv4_address: 172.20.0.4
    mem_limit: 8g
    cpus: 4.0
    working_dir: /app  # 设置工作目录
    command: ["/app/entrypoint.sh", "gunicorn", "--reload", "-b", "0.0.0.0:8000", "lbu_api.wsgi:application"]
networks:
  lbu_net:
    external: true


------------------------------------------------
创建网络
docker network create --subnet=172.20.0.0/16 lbu_net
查看所有容器资源限制
docker ps -q | xargs docker inspect --format '{{.Name}} -> CPU: {{.HostConfig.NanoCpus}}  MEM: {{.HostConfig.Memory}}'
查看网络
docker network ls
查看容器网络及ip
docker ps -q | xargs -I {} docker inspect --format '{{.Name}}: {{range $k, $v := .NetworkSettings.Networks}}网络名={{$k}} | IP={{$v.IPAddress}}{{"\n"}}{{end}}' {}
查看所有网络ip段
docker network ls -q | xargs -I {} docker network inspect {} --format '网络: {{.Name}} | 子网: {{range .IPAM.Config}}{{.Subnet}}{{end}} | 网关: {{range .IPAM.Config}}{{.Gateway}}{{end}} | 驱动: {{.Driver}}'

docker exec -it zh_mongodb mongosh -u admin -p 'Shimujiuxia' --authenticationDatabase admin
------------------------------------------------
创建数据库
services:
  mysql:
    image: registry.cn-hangzhou.aliyuncs.com/leiuvn/mysql:8.4.5
    container_name: mysql8
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: Shimujiuxia@2028
    ports:
      - "3306:3306"
    volumes:
      - /data/wwwroot/mysql_data:/var/lib/mysql
    networks:
      lbu_net:
        ipv4_address: 172.20.0.2
    mem_limit: 16g
    cpus: 4.0

networks:
  lbu_net:
    external: true
    
    
------------------------------------------------
新建数据库
CREATE DATABASE lbu_api DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

如库已存在修改
ALTER DATABASE lbu_api CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE USER 'lbu'@'%' IDENTIFIED BY 'Shimujiuxia@2028';

CREATE DATABASE IF NOT EXISTS lbu;

GRANT ALL PRIVILEGES ON lbu_api.* TO 'lbu'@'%';
REVOKE ALL PRIVILEGES ON lbu_api.* FROM 'lbu'@'%';

FLUSH PRIVILEGES;


------------------------------------------------
去项目目录配置
开发环境解决admin无css样式问题
vim entrypoint.sh
# 执行 collectstatic 收集静态文件
python manage.py collectstatic --noinput

vim settings.py
import os
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

vim urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    
生产环境
拷贝staticfiles目录到代理nginx,增加以下代理,修改setting.py中DEBUG = True的True为False
    location /static/ {
        root /usr/share/nginx/html/lbu_api/;
        access_log off;
        expires 30d;
    }


------------------------------------------------
允许域名登录,不加登录admin后台报错
ALLOWED_HOSTS = ["api.lbu.cn","172.22.0.10"]
CSRF_TRUSTED_ORIGINS = [
    "http://api.lbu.cn",
    "https://api.lbu.cn",
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 指定 MySQL 数据库引擎
        'NAME': 'lbu_api',  # 数据库名称
        'USER': 'lbu',  # MySQL 用户名
        'PASSWORD': 'Shimujiuxia@2028',  # MySQL 密码
        'HOST': '172.20.0.2',  # MySQL 服务器地址(本机用 localhost,远程服务器填写 IP)
        'PORT': '3306',  # MySQL 端口号,默认 3306
        'OPTIONS': {
            'charset': 'utf8mb4',  # 设置字符集,支持 Emoji
        },
    }
}


------------------------------------------------
vim entrypoint.sh
重点:创建到项目目录
#!/bin/bash

# 等待数据库启动(适用于 PostgreSQL / MySQL)
echo "Waiting for database..."
sleep 5  # 可根据情况调整等待时间

# 执行 collectstatic 收集静态文件
python manage.py collectstatic --noinput

# 运行数据库迁移
echo "Applying database migrations..."
python manage.py migrate

# 创建超级用户(如果不存在)
echo "Creating superuser..."
python manage.py shell <<EOF
import os
from django.contrib.auth import get_user_model

User = get_user_model()
username = os.getenv("DJANGO_SUPERUSER_USERNAME", "admin")
email = os.getenv("DJANGO_SUPERUSER_EMAIL", "lmor@qq.com")
password = os.getenv("DJANGO_SUPERUSER_PASSWORD", "Shimujiuxia@2028")

if not User.objects.filter(username=username).exists():
    User.objects.create_superuser(username, email, password)
    print(f"Superuser {username} created!")
else:
    print(f"Superuser {username} already exists.")
EOF

# 启动 Django 服务器(或 Gunicorn)
echo "Starting Django server..."
exec "$@"


------------------------------------------------
安装mysql及驱动
旧版本mysqlclient
pip install mysqlclient==2.1.1

新版本mysqlclien,安装容易失败
pip install mysqlclient -i https://mirrors.aliyun.com/pypi/simple/

或者安装pymysql
pip install pymysql
vim /data/lab_api/lab_django/lab_django/settings.py
import pymysql
pymysql.install_as_MySQLdb()

生产环境通常用Gunicorn来运行Django
pip install gunicorn
gunicorn --workers 4 --bind 0.0.0.0:8000 lab_django.wsgi:application


------------------------------------------------
django跨域
pip install django-cors-headers
vim settings.py

#添加corsheaders到INSTALLED_APPS
INSTALLED_APPS = [
    'corsheaders',
]
#添加CorsMiddleware到MIDDLEWARE靠前
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]
#允许所有域名访问
CORS_ALLOW_ALL_ORIGINS = True
#允许特定域名访问
CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]
#允许的请求方法,选择配置
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
#允许的请求头,选择配置
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]


------------------------------------------------
nginx配置转发
yum install -y pcre pcre-devel zlib zlib-devel openssl openssl-devel

./configure \
    --prefix=/opt/nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_gzip_static_module \
    --with-stream \
    --with-pcre

make && make install

config
include /opt/nginx/conf/vhost/*.conf;
server {
    listen 80;
    server_name shilei.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}


------------------------------------------------
nginx开机启动
vim /etc/systemd/system/nginx.service

[Unit]
Description=The Nginx HTTP Server
After=network.target

[Service]
ExecStart=/opt/nginx/sbin/nginx
ExecReload=/opt/nginx/sbin/nginx -s reload
ExecStop=/opt/nginx/sbin/nginx -s quit
Restart=always
Type=forking

[Install]
WantedBy=multi-user.target

sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx


------------------------------------------------
supervisor进程管理
yum -y install supervisor
systemctl start supervisord
systemctl enable supervisord

vim /etc/supervisord.conf
[include]
#files = supervisord.d/*.ini
files = /etc/supervisor/conf.d/*.conf

mkdir -p /etc/supervisor/conf.d

vim /etc/supervisor/conf.d/gunicorn.conf
[program:gunicorn]
command=/data/lab_api/lab/bin/gunicorn --workers 4 --bind 0.0.0.0:8000 lab_django.wsgi:application
directory=/data/lab_api/lab_django
autostart=true
autorestart=true
stderr_logfile=/var/log/gunicorn.err.log
stdout_logfile=/var/log/gunicorn.out.log
user=root
environment=PATH="/data/lab_api/lab/bin"


supervisorctl reload
systemctl restart supervisord
supervisorctl start gunicorn


------------------------------------------------
创建合并代码app,git_operations
cd lab_django
python manage.py startapp git_operations

lab_web后端代码
安装paramiko库
pip install paramiko

将以下代码放到app目录git_operations/views.py

import paramiko
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt
def merge_branch(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            platform_name = data.get("platform_name")
            source_branch = data.get("source_branch")
            target_branch = data.get("target_branch")

            if not platform_name or not source_branch or not target_branch:
                return JsonResponse({"error": "Missing parameters"}, status=400)

            if platform_name == "vip.yaozh.com":
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

                hostname = "1.1.1.1"
                username = "your_user"
                password = "your_password"  # 建议使用 SSH Key 代替密码

                try:
                    ssh.connect(hostname, username=username, password=password, timeout=10)

                    commands = [
                        "cd /data/wwwroot/vip.yaozh.com",
                        "git checkout master",
                        f"git merge {source_branch} {target_branch}"
                    ]
                    command = " && ".join(commands)

                    stdin, stdout, stderr = ssh.exec_command(command)
                    output = stdout.read().decode()
                    error = stderr.read().decode()

                    ssh.close()

                    if error:
                        return JsonResponse({"error": error}, status=500)
                    return JsonResponse({"message": "Merge successful", "output": output})

                except Exception as e:
                    return JsonResponse({"error": str(e)}, status=500)

            else:
                return JsonResponse({"message": "No action needed for this platform."})

        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON"}, status=400)

    return JsonResponse({"error": "Invalid request method"}, status=405)

在git_operations/urls.py添加路由
from django.urls import path
from .views import merge_branch

urlpatterns = [
    path("merge_branch/", merge_branch, name="merge_branch"),
]

在lab_django/lab_django/urls.py注册api/路由
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/", include("git_operations.urls")),
]

在lab_django/lab_django/settings.py注册git_operations
INSTALLED_APPS = [
    ...
    "git_operations",
]


------------------------------------------------
curl请求测试
curl -X POST "http://10.10.10.2:8000/api/merge_branch/" -H "Content-Type: application/json" -d '{"platform": "lei",  "source_branch": "develop", "target_branch": "master"}'

设置环境变量
export GITLAB_PRIVATE_TOKEN=osbxMgMpocGpChQkLxZL
echo $GITLAB_PRIVATE_TOKEN


------------------------------------------------
1.多个vue子页面
npm install vue-router

2.定义路由
vim ./src/router/index.js

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

const routes = [
  { path: '/', component: Home }, // 主页
  { path: '/about', component: About }, // 关于页
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

3.引入路由
vim src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App);
app.use(router);
app.mount('#app');

4.App中配置
vim src/App.vue

<template>
  <div id="app">
    <nav>
      <router-link to="/">首页</router-link> |
      <router-link to="/about">关于</router-link>
    </nav>
    <router-view></router-view>
  </div>
</template>

<style>
nav {
  margin-bottom: 20px;
}
</style>

5.在src/views目录下建两个vue组件
src/views/Home.vue
<template>
  <div>
    <h1>首页</h1>
    <p>欢迎来到首页!</p>
  </div>
</template>

src/views/About.vue
<template>
  <div>
    <h1>关于我们</h1>
    <p>这里是关于页面。</p>
  </div>
</template>


------------------------------------------------



0 篇评论

发表我的评论