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.
61 lines
1.5 KiB
61 lines
1.5 KiB
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_records(self, table_name: str) -> list[dict]:
|
|
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")
|
|
]
|
|
DedicatedDatabaseConnection = Annotated[
|
|
MyDatabaseConnection,
|
|
Depends(get_database_connection, dependency_scope="lifespan", use_cache=False),
|
|
]
|
|
|
|
|
|
@app.get("/groups/")
|
|
async def read_groups(database_connection: DedicatedDatabaseConnection):
|
|
return await database_connection.get_records("groups")
|
|
|
|
|
|
@app.get("/users/")
|
|
async def read_users(database_connection: DedicatedDatabaseConnection):
|
|
return await database_connection.get_records("users")
|
|
|
|
|
|
@app.get("/items/")
|
|
async def read_items(database_connection: GlobalDatabaseConnection):
|
|
return await database_connection.get_records("items")
|
|
|
|
|
|
@app.get("/items/{item_id}")
|
|
async def read_item(
|
|
database_connection: GlobalDatabaseConnection, item_id: Annotated[str, Path()]
|
|
):
|
|
return await database_connection.get_record("items", item_id)
|
|
|