"""Configure Gunicorn to run the ASGI server.Uses Uvicorn as the worker for the Poiesis API."""importimportlibimportmultiprocessingfromgunicorn.app.baseimportBaseApplicationfrompoiesis.api.constantsimportget_poiesis_api_constantsfrompoiesis.constantsimportget_poiesis_constantsconstants=get_poiesis_constants()api_constants=get_poiesis_api_constants()BIND=f"{api_constants.Gunicorn.HOST}:{api_constants.Gunicorn.PORT}"WORKERS=api_constants.Gunicorn.WORKERSor(multiprocessing.cpu_count()*2)+1TIMEOUT=api_constants.Gunicorn.TIMEOUTWORKER_CLASS="uvicorn.workers.UvicornWorker"
[docs]defimport_app_from_string(import_string):"""Import an application object from a string. Args: import_string (str): The import string in the format "<module>:<attribute>". Returns: Any: The imported attribute object. Raises: ImportError: If the import string is invalid or the attribute is not found. """module_str,_,attrs_str=import_string.partition(":")ifnotmodule_strornotattrs_str:raiseImportError(f"Import string '{import_string}' must be in format '<module>:<attribute>'")try:module=importlib.import_module(module_str)exceptImportErrorasexc:ifexc.name!=module_str:raiseexcfromNoneraiseImportError(f"Could not import module '{module_str}'")fromexctry:forattrinattrs_str.split("."):module=getattr(module,attr)returnmoduleexceptAttributeErrorasexc:raiseImportError(f"Attribute '{attrs_str}' not found in module '{module_str}'")fromexc
[docs]defrun():"""Run the Gunicorn server with the Poiesis app."""classPoiesisApplication(BaseApplication):def__init__(self,app_import_path,options=None):self.options=optionsor{}self.app_import_path=app_import_pathsuper().__init__()defload_config(self):# type: ignore[override]forkey,valueinself.options.items():ifself.cfgandkeyinself.cfg.settingsandvalueisnotNone:self.cfg.set(key.lower(),value)defload(self):# type: ignore[override]returnimport_app_from_string(self.app_import_path)options={"bind":BIND,"workers":int(WORKERS),"timeout":int(TIMEOUT),"worker_class":WORKER_CLASS,}app_import_path="poiesis.api.app:app"PoiesisApplication(app_import_path,options).run()