Debian Codegraph @

docs_src/dependencies/tutorial008c_an_py310.py

raw
1 from typing import Annotated
2
3 from fastapi import Depends, FastAPI, HTTPException
4
5 app = FastAPI()
6
7
8 class InternalError(Exception):
9 pass
10
11
12 def get_username():
13 try:
14 yield "Rick"
15 except InternalError:
16 print("Oops, we didn't raise again, Britney 😱")
17
18
19 @app.get("/items/{item_id}")
20 def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
21 if item_id == "portal-gun":
22 raise InternalError(
23 f"The portal gun is too dangerous to be owned by {username}"
24 )
25 if item_id != "plumbus":
26 raise HTTPException(
27 status_code=404, detail="Item not found, there's only a plumbus here"
28 )
29 return item_id