Last active
December 2, 2025 22:02
-
-
Save egorbarakhov/cc6717087c31171da8ce095d405f8f8a to your computer and use it in GitHub Desktop.
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
| import asyncio | |
| from dataclasses import dataclass, field | |
| from typing import ClassVar, Self | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import uvicorn | |
| class STaskBase(BaseModel): | |
| name: str | |
| desc: str | None = None | |
| class STaskAdd(STaskBase): | |
| ... | |
| class STask(STaskBase): | |
| id: int | |
| @dataclass(frozen=True) | |
| class TaskList: | |
| tasks: list[STask] = field(default_factory=list) | |
| _instance: ClassVar[Self | None] = field(default=None, init=False) | |
| _lock: ClassVar[asyncio.Lock] = field(default=asyncio.Lock(), init=False) | |
| def __new__(cls, *_args, **_kwargs) -> Self: | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| return cls._instance | |
| async def add(self, task_add: STaskAdd) -> STask: | |
| async with self._lock: | |
| next_id = len(self.tasks) + 1 | |
| task = STask(**{"id": next_id, **task_add.model_dump()}) | |
| self.tasks.append(task) | |
| return task | |
| app = FastAPI() | |
| task_list = TaskList() | |
| # have to alias to pass tests | |
| tasks = task_list.tasks | |
| @app.post("/tasks") | |
| async def create(task: STaskAdd) -> STask: | |
| return await task_list.add(task) | |
| if __name__ == "__main__": | |
| uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment