Debian Codegraph @

docs_src/dependencies/tutorial008c_py310.py

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