Run startup code in the parent with Django and Gun

2019-05-17 02:25发布

问题:

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.