Skip to content

Instantly share code, notes, and snippets.

@Kludex
Last active March 29, 2024 12:31
Show Gist options
  • Save Kludex/c98ed6b06f5c0f89fd78dd75ef58b424 to your computer and use it in GitHub Desktop.
Save Kludex/c98ed6b06f5c0f89fd78dd75ef58b424 to your computer and use it in GitHub Desktop.
Run Gunicorn with Uvicorn workers in code
""" 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)
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