Search code examples
djangogunicornuwsgiwsgidjango-wsgi

What is the lifetime of a Django WSGI application object when served using Gunicorn or uWSGI?


I'm using Django with Gunicorn. Since I don't know much about the Gunicorn internals, so I'm wondering what is the lifetime of an WSGI application object. Is it forever, or created for every request, or lives as long as the worker lives?

Similarly in uWSGI seems to invoke an application callable for one request as per this. So, does this mean that application objects lives for a while (and uWSGI invokes the same object for every request)?

This might be stupid but I'm trying to figure this out while trying to cache some stuff (let's say in some global or file level variables) at the application level to avoid cache (Redis/Memcached) or db calls. I'm wondering if application object lives for at least some time, then may be a good thing to cache data at regular intervals without making cache requests (after all it's a N/W request) as well.

Please help me understand this.


Solution

  • You seem to be missing some important distinctions -- WSGI is the name of the protocol as dictated by PEP-333(3), and gunicorn/uwsgi are implementations of the said protocol.

    what is the lifetime of an WSGI application object. Is it forever, or created for every request, or lives as long as the worker lives?

    Django has wsgi.py file that exposes the WSGI application object named application, and all USGI servers use that (you need to pass the location of this callable). The basic criterion is that the application object needs to take two arguments:

    • the WSGI environment
    • a callable to start the response

    The application wraps everything for the layers below by generating request and other necessary metadata from the environment, and while it's time to send the response it calls the callable provided with the status code and headers. Then the response body goes as an iterable.

    So as you can see, the WSGI servers can get the application object while starting up and can call that each time a request comes to get response, throughout the lifetime of the server process. I've used uwsgi mostly, so I can tell uwsgi (and presumably others) does exactly that.

    To give you more context on this, uwsgi has the concept of a master process starting worker processes and spawning worker threads inside each of the processes. gunicorn (and others) presumably has a similar concept if not exactly the same.