Search code examples
pythonpython-asynciofastapigunicornuvicorn

How to pass worker options/parameters in gunicorn


I am running an app which needed uvicorn's asycio loop, by default it uses auto and some time it randomly assign it to uvloop whihc breaks the behavior. So I use the following command

uvicorn myapp.server.api:app --loop asyncio --port 7474

This forces uvicorn to use asyncio loop. This works as expected.

Now I am trying to move this changes to gunicorn and uvicorn as worker, but I am couldn't find a way to pass this loop to uvicorn.

gunicorn myapp.server.api:app  -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:7474

But this end up using default value i.e. auto and end up selecting loop type as uvloop. How can I force it to use asyncio worker. Help is appreciated.


Solution

  • The problem is gunicorn does not support passing options directly to uvicorn workers.

    So, basically, you can create a custom UvicornWorker class where you override the default loop policy.

    Here's an example:

    # myapp/server/custom_worker.py
    
    from uvicorn.workers import UvicornWorker
    
    class CustomUvicornWorker(UvicornWorker):
        CONFIG_KWARGS = {"loop": "asyncio"}
    

    Then:

    gunicorn myapp.server.api:app -k myapp.server.custom_worker.CustomUvicornWorker --bind 0.0.0.0:7474