在源代码更改上自动重载

最后,我将开发 env 从 runserver 迁移到 gunicorn/nginx。

将 runserver 的自动重载功能复制到 gunicorn 会很方便,因此当源代码发生变化时,服务器会自动重新启动。否则,我必须用 kill -HUP手动重新启动服务器。

有办法避免手动重启吗?

73681 次浏览

一种选择是使用 最高要求,通过将 --max-requests 1添加到启动选项,将每个衍生进程限制为只为一个请求提供服务。每个新产生的进程都应该看到代码的更改,并且在开发环境中,每个请求的额外启动时间应该可以忽略不计。

Bryan Helmig 提出了这个想法,我修改了它,使用 run_gunicorn而不是直接启动 gunicorn,这样就可以将这3个命令剪切并粘贴到 django 项目根文件夹中的 shell 中(同时激活 viralenv) :

pip install watchdog -U
watchmedo shell-command --patterns="*.py;*.html;*.css;*.js" --recursive --command='echo "${watch_src_path}" && kill -HUP `cat gunicorn.pid`' . &
python manage.py run_gunicorn 127.0.0.1:80 --pid=gunicorn.pid

虽然这是一个老问题,但是您需要知道,自从版本19.0 gunicorn就有了 --reload选项。 所以现在不需要第三方工具了。

我使用 git push 部署到生产环境,并设置 git 挂钩来运行脚本。这种方法的优点是您还可以同时进行迁移和包安装。https://mikeeverhart.net/2013/01/using-git-to-deploy-code/

mkdir -p /home/git/project_name.git
cd /home/git/project_name.git
git init --bare

然后创建一个脚本 /home/git/project_name.git/hooks/post-receive

#!/bin/bash
GIT_WORK_TREE=/path/to/project git checkout -f
source /path/to/virtualenv/activate
pip install -r /path/to/project/requirements.txt
python /path/to/project/manage.py migrate
sudo supervisorctl restart project_name

确保 chmod u+x post-receive,并添加用户到 sudoers。允许它运行 sudo supervisorctl没有密码

在我的本地/开发服务器上,我设置了 git remote,允许我推送到生产服务器

git remote add production ssh://user_name@production-server/home/git/project_name.git


# initial push
git push production +master:refs/heads/master


# subsequent push
git push production master

作为奖励,您将在脚本运行时看到所有提示。因此,您将看到迁移/包安装/主管重新启动是否有任何问题。