|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +from gunicorn.app.base import BaseApplication |
| 4 | +from gunicorn.util import import_app |
| 5 | +from uvicorn.workers import UvicornWorker as BaseUvicornWorker |
| 6 | + |
| 7 | +try: |
| 8 | + import uvloop # noqa: WPS433 (Found nested import) |
| 9 | +except ImportError: |
| 10 | + uvloop = None # type: ignore # noqa: WPS440 (variables overlap) |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +class UvicornWorker(BaseUvicornWorker): |
| 15 | + """ |
| 16 | + Configuration for uvicorn workers. |
| 17 | +
|
| 18 | + This class is subclassing UvicornWorker and defines |
| 19 | + some parameters class-wide, because it's impossible, |
| 20 | + to pass these parameters through gunicorn. |
| 21 | + """ |
| 22 | + |
| 23 | + CONFIG_KWARGS = { # noqa: WPS115 (upper-case constant in a class) |
| 24 | + "loop": "uvloop" if uvloop is not None else "asyncio", |
| 25 | + "http": "httptools", |
| 26 | + "lifespan": "on", |
| 27 | + "factory": True, |
| 28 | + "proxy_headers": False, |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | +class GunicornApplication(BaseApplication): |
| 33 | + """ |
| 34 | + Custom gunicorn application. |
| 35 | +
|
| 36 | + This class is used to start guncicorn |
| 37 | + with custom uvicorn workers. |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__( # noqa: WPS211 (Too many args) |
| 41 | + self, |
| 42 | + app: str, |
| 43 | + host: str, |
| 44 | + port: int, |
| 45 | + workers: int, |
| 46 | + **kwargs: Any, |
| 47 | + ): |
| 48 | + self.options = { |
| 49 | + "bind": f"{host}:{port}", |
| 50 | + "workers": workers, |
| 51 | + "worker_class": "{{cookiecutter.project_name}}.gunicorn_runner.UvicornWorker", |
| 52 | + **kwargs |
| 53 | + } |
| 54 | + self.app = app |
| 55 | + super().__init__() |
| 56 | + |
| 57 | + def load_config(self) -> None: |
| 58 | + """ |
| 59 | + Load config for web server. |
| 60 | +
|
| 61 | + This function is used to set parameters to gunicorn |
| 62 | + main process. It only sets parameters that |
| 63 | + gunicorn can handle. If you pass unknown |
| 64 | + parameter to it, it crash with error. |
| 65 | + """ |
| 66 | + for key, value in self.options.items(): |
| 67 | + if key in self.cfg.settings and value is not None: |
| 68 | + self.cfg.set(key.lower(), value) |
| 69 | + |
| 70 | + def load(self) -> str: |
| 71 | + """ |
| 72 | + Load actual application. |
| 73 | +
|
| 74 | + Gunicorn loads application based on this |
| 75 | + function's returns. We return python's path to |
| 76 | + the app's factory. |
| 77 | +
|
| 78 | + :returns: python path to app factory. |
| 79 | + """ |
| 80 | + return import_app(self.app) |
0 commit comments