Created
March 21, 2023 13:53
-
-
Save bedilbek/a7bc6a119f3ddd06765101c2e0dd968f to your computer and use it in GitHub Desktop.
Fast API template
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
| # taken from https://github.com/tiangolo/fastapi/issues/617#issuecomment-840626819 | |
| from dataclasses import dataclass | |
| from functools import partial | |
| from typing import Optional | |
| from fastapi import FastAPI | |
| from pydantic import BaseSettings | |
| class Config(BaseSettings): | |
| id: str | |
| password: str | |
| @dataclass | |
| class ClassifyUtil: | |
| id: str | |
| password: str | |
| async def expensive_initialization(self): | |
| class_name = self.__class__.__name__ | |
| print(f"Initialising {class_name}") | |
| async def startup(app: FastAPI): | |
| config: Config = app.state.config | |
| classify_util = ClassifyUtil(config.id, config.password) | |
| await classify_util.expensive_initialization() | |
| app.state.classify_util = classify_util | |
| def create_app(config: Optional[Config] = None) -> FastAPI: | |
| if config is None: | |
| config = Config() # Calling `Config()` will read `id` and `password` from the environment | |
| app = FastAPI() | |
| app.state.config = config | |
| app.add_event_handler(event_type="startup", func=partial(startup, app=app)) | |
| return app | |
| app = create_app() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment