0xBF
0xBF

0xBF

Run Gunicorn with Gevent

0xBF's photo
0xBF

Published on May 26, 2021

1 min read

Gunicorn + Gevent

If you already have a wsgi application written in Flask/Django/Webpy, and you want to run it with gunicorn, suppose your application variable is in wsgi.py file:

$ pip install gunicorn
$ gunicorn -w 2 wsgi:application

By default guicorn is running in sync mode, if your application is I/O bound, use gevent mode may increase its performance:

$ pip install gunicorn
$ pip install gevent
$ gunicorn -w 2 -k gevent wsgi:application

You don't even need to change your code. If you searched this, some other articles may mention you need to add code to do a "monkey patch", e.g. if your gunicorn's configure file is gunicorn_conf.py, then add this to that file:

from gevent import monkey
monkey.patch_all()

BUT you really don't need to add this, because gunicorn will auto path this, here is the code snippet from gunicorn:

from gevent import hub, monkey, socket, pywsgi

class GeventWorker(AsyncWorker):
    ...
    def patch(self):
        monkey.patch_all()
        ...
    ...

    def init_process(self):
        self.patch()
        hub.reinit()
        super().init_process()

So you can see in the init_process function, guinicorn will call the patch function, which will call the monkey.patch_all() function.

In short, to run gunicorn with gevent, you only need to install the gevent package and change the worker_class to be "gevent".

Reference:

 
Share this