Run startup code in the parent with Django and Gunicorn

本小妞迷上赌 提交于 2019-12-07 17:35:39

问题


I need my code run at Django application startup, before Django starts listening for incoming connections. Running my code upon the first HTTP request is not good enough. When I use Gunicorn, my code must run in the parent process, before it forks.

https://stackoverflow.com/a/2781488/97248 doesn't seem to work in Django 1.4.2: it doesn't run the Middleware's __init__ method until the first request is received. Ditto for adding code to urls.py.

A quick Google search didn't reveal anything useful.


回答1:


I have just run into this problem myself, and the solution was to basically chain the commands to guarantee execution and correct order:

Script started by systemd, supervisord or any other such system:

#!/bin/sh
python manage.py my_custom_command && gunicorn project.wsgi $@

Create your own custom django command and off you go. You can get some speedups if you disable sanity checks in the command (requires_system_checks and requires_migrations_checks set to False).

To make things more generic, you could create a "boot" signal to which you connect arbitrary functions, and just emit the signal from this custom command.



来源:https://stackoverflow.com/questions/13768894/run-startup-code-in-the-parent-with-django-and-gunicorn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!