Django uwsgi 基础知识

编写uwsgi,nginx配置文件

如下配置,保存在项目根目录下的uwsgi,ini中,其中%d的含义为“包含配置文件的目录的绝对路径”(结尾是/),%n是“不带扩展名的文件名”

[uwsgi]
socket = %d%n/django.sock
chmod-socket = 666
processes = %k
pidfile = %d%n/master.pid
touch-logreopen = %dsplitlog.py
daemonize = %d%n/run.log
chdir = /website/proxy/
wsgi-file = proxy/wsgi.py
virtualenv = venv
# clear environment on exit
# like pid or unix socket
vacuum = true

然后在/etc/nginx/conf.d/proxy.conf中这样写

server {
    listen 80 default_server;
    server_name example.com;

    client_max_body_size 200M;

    location / {
        include uwsgi_params;
        uwsgi_pass unix://app/django.sock;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-Port $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static/ {
        alias /app/static/;
    }

    location /media/ {
        alias /app/media/;
    }
}

uwsgi_pass的值和uwsgi.ini配置中socket的值必须一致。

uwsgi开机启动

使用 vi /etc/init.d/uwsgi写入

#!/bin/bash
# chkconfig: - 85 15
conf=配置文件路径
pid=pidfile路径
case $1 in
    start)
        cd $path
        uwsgi $conf
    ;;

    stop)
        uwsgi --stop $pid
    ;;

    show)
        ps -ef|grep uwsgi
    ;;

    reload)
        uwsgi --reload $pid
    ;;

    *)
        echo -n "Usage: $0 {start|restart|stop|show}"
    ;;

esac
sudo chmod +x /etc/init.d/uwsgi
sudo chkconfig --add uwsgi
sudo chkconfig uwsgi on

最后,使用命令sudo service uwsgi start和sudo service nginx start开启网站。

自动分割日志

uwsgi是一个很棒的程序,它能轻易的驱动任何支持WSGI协议的应用程序。但它默认的日志系统不能配置按天分割。那么我稍微查了一下资料,写了这篇文章以做记录,方便他日再用。

首先,最重要的是uwsgi配置的touch-logreopen选项,它指定监听一个文件,当这个文件的修改日期有变化时,就会重新打开日志文件。

uwsgi配置类似于

[uwsgi]
socket = %d%n/django.sock
chmod-socket = 666
processes = %k
pidfile = %d%n/master.pid
touch-logreopen = %dsplitlog.py
daemonize = %d%n/run.log
# clear environment on exit
# like pid or unix socket
vacuum = true
chdir = /website/account/
wsgi-file = main/wsgi.py
virtualenv = .venv/

利用这一点,可以考虑写一个脚本,每天0点执行。

import os
import shutil
import datetime

SELF = os.path.abspath(__file__)
BASE_PATH = os.path.dirname(SELF)


def yesterday():
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today-oneday
    return yesterday.strftime("%Y-%m-%d")


for each in os.listdir(BASE_PATH):
    path = os.path.join(BASE_PATH, each)
    if os.path.isdir(path):
        run_log = os.path.join(path, "run.log")
        if os.path.exists(run_log):
            yesterday_log = os.path.join(path, yesterday() + ".log")
            shutil.move(run_log, yesterday_log)

with open(SELF, "rb+") as file:
    all = file.read()
    file.seek(0, 0)
    file.write(all)

然后再创建一个splitlogTask,写入以下内容

0 0 * * * /usr/bin/python3 /website/uwsgi.d/splitlog.py

使用crontab splitlogTask注册这个定时任务即可。

posted @ 2020-05-12 23:33  呓语i  阅读(501)  评论(0编辑  收藏  举报