FastAPI With SQLite
Trying to get FastAPI to work with asynchronous queries to an SQLight database (rough notes).
EDIT: I was onto something with Depends(), but the way I’ve got things setup here would create an
AsyncHttpClient for each request. A better approach is outlined at
notes / FastAPI with
Chroma.
FastAPI dependencies — Depends()
https://fastapi.tiangolo.com/reference/dependencies/#depends
Dependencies are handled with the special function Depends() that takes a callable:
from fastapi import Depends
fastapi.Depends signature:
Depends(dependency=None, *, use_cache=True, scope=None)
Don’t call it directly, FastAPI calls the dependency function:
async def get_db_connection() -> aiosqlite.Connection | Any:
db = await aiosqlite.connect(db_path)
db.row_factory = aiosqlite.Row
try:
yield db
finally:
await db.close()
@app.post("/query", response_class=HTMLResponse)
async def query_collection(
query: Annotated[str, Form()],
db: aiosqlite.Connection = Depends(get_db_connection, scope="function"),
):
cursor = await db.execute("SELECT html_heading FROM sections")
row = await cursor.fetchone()
print(row[0]) if row else None
Read the docs (
https://fastapi.tiangolo.com/reference/dependencies/#depends
) for details about the
Depends() method’s params. Useful for my case:
scope: Mainly used for dependencies withyield, define when the dependency function should start (the code beforeyield) and when it should end (the code afteryield)."function": the dependency function will be executed around the path operation function"request": the dependency function will be executed around the request and response cycle
Note that the yield expression on async def get_db_connection() causes the function to return an
asynchronous generator function. See
notes / The Python yield keyword (Yield expressions in
async functions)
for details.