Debian Codegraph @

docs_src/dependencies/tutorial014_an_py310.py

raw
1 import time
2 from typing import Annotated
3
4 from fastapi import Depends, FastAPI, HTTPException
5 from fastapi.responses import StreamingResponse
6 from sqlmodel import Field, Session, SQLModel, create_engine
7
8 engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db")
9
10
11 class User(SQLModel, table=True):
12 id: int | None = Field(default=None, primary_key=True)
13 name: str
14
15
16 app = FastAPI()
17
18
19 def get_session():
20 with Session(engine) as session:
21 yield session
22
23
24 def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
25 user = session.get(User, user_id)
26 if not user:
27 raise HTTPException(status_code=403, detail="Not authorized")
28 session.close()
29
30
31 def generate_stream(query: str):
32 for ch in query:
33 yield ch
34 time.sleep(0.1)
35
36
37 @app.get("/generate", dependencies=[Depends(get_user)])
38 def generate(query: str):
39 return StreamingResponse(content=generate_stream(query))