Last active
May 16, 2025 06:21
-
-
Save Kludex/c98ed6b06f5c0f89fd78dd75ef58b424 to your computer and use it in GitHub Desktop.
Run Gunicorn with Uvicorn workers in code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Snippet that demonstrates how to use Gunicorn with Uvicorn workers in code. | |
Feel free to run: | |
- `python main.py` - to use uvicorn. | |
- `ENV=prod python main.py` - to use gunicorn with uvicorn workers. | |
Reference: https://docs.gunicorn.org/en/stable/custom.html | |
""" | |
import multiprocessing | |
import os | |
from typing import Any, Callable, Dict | |
import uvicorn | |
from fastapi import FastAPI | |
from gunicorn.app.base import BaseApplication | |
app = FastAPI() | |
@app.get("/") | |
async def home(): | |
return "Hello World!" | |
def number_of_workers(): | |
return (multiprocessing.cpu_count() * 2) + 1 | |
class StandaloneApplication(BaseApplication): | |
def __init__(self, application: Callable, options: Dict[str, Any] = None): | |
self.options = options or {} | |
self.application = application | |
super().__init__() | |
def load_config(self): | |
config = { | |
key: value | |
for key, value in self.options.items() | |
if key in self.cfg.settings and value is not None | |
} | |
for key, value in config.items(): | |
self.cfg.set(key.lower(), value) | |
def load(self): | |
return self.application | |
if __name__ == "__main__": | |
if os.getenv("ENV") == "prod": | |
options = { | |
"bind": "%s:%s" % ("127.0.0.1", "8000"), | |
"workers": number_of_workers(), | |
"worker_class": "uvicorn.workers.UvicornWorker", | |
} | |
StandaloneApplication(app, options).run() | |
else: | |
uvicorn.run("main:app", reload=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gunicorn==20.1.0 | |
uvicorn==0.14.0 | |
fastapi==0.66.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anyone who want to use factory-pattern instead, replace
self.application
withself.application()
in L47.