ben ben - 3 months ago 14
Python Question

Gunicorn with multiple workers: Is there an easy way to execute certain code only once?

If I start gunicorn with

-w 4
with an app with the content

print 'hello'


it will print four times
'hello'
. Is there some way to coordinate this in such a way that only one
'hello'
is printed? I want to do some cleanup on start which I'd like to be only executed once.

Answer

You can write a server hook, for example on_starting, which will run in the master process and thus only happen once.

I think these only work if you're using a Python script for configuration, like in their example.


(This is the OP speaking):

What worked for me was to create a config file "my_conf.py" with the content:

def on_starting(server):
     print(1)

Then

gunicorn [...] -w 2 -c my_conf.py &

prints "1" only once on server start although two workers were specified to be used.

Comments