pythonasyncioapiasyncfastapiframeworkjsonjson-schemaopenapiopenapi3pydanticpython-typespython3redocreststarletteswaggerswagger-uiuvicornweb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1005 B
43 lines
1005 B
from typing import Annotated
|
|
|
|
from fastapi import Depends, FastAPI, Path
|
|
from typing_extensions import Self
|
|
|
|
|
|
class MyDatabaseConnection:
|
|
"""
|
|
This is a mock just for example purposes.
|
|
"""
|
|
|
|
async def __aenter__(self) -> Self:
|
|
return self
|
|
|
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
pass
|
|
|
|
async def get_record(self, table_name: str, record_id: str) -> dict:
|
|
pass
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
async def get_database_connection():
|
|
async with MyDatabaseConnection() as connection:
|
|
yield connection
|
|
|
|
|
|
GlobalDatabaseConnection = Annotated[
|
|
MyDatabaseConnection, Depends(get_database_connection, dependency_scope="lifespan")
|
|
]
|
|
|
|
|
|
async def get_user_record(
|
|
database_connection: GlobalDatabaseConnection, user_id: Annotated[str, Path()]
|
|
) -> dict:
|
|
return await database_connection.get_record("users", user_id)
|
|
|
|
|
|
@app.get("/users/{user_id}")
|
|
async def read_user(user_record: Annotated[dict, Depends(get_user_record)]):
|
|
return user_record
|
|
|