Coverage for docs_src/dependencies/tutorial008b.py: 100%
18 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from fastapi import Depends, FastAPI, HTTPException 1abcde
3app = FastAPI() 1abcde
6data = { 1abcde
7 "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
8 "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
9}
12class OwnerError(Exception): 1abcde
13 pass 1abcde
16def get_username(): 1abcde
17 try: 1abcde
18 yield "Rick" 1abcde
19 except OwnerError as e: 1abcde
20 raise HTTPException(status_code=400, detail=f"Owner error: {e}") 1abcde
23@app.get("/items/{item_id}") 1abcde
24def get_item(item_id: str, username: str = Depends(get_username)): 1abcde
25 if item_id not in data: 1abcde
26 raise HTTPException(status_code=404, detail="Item not found") 1abcde
27 item = data[item_id] 1abcde
28 if item["owner"] != username: 1abcde
29 raise OwnerError(username) 1abcde
30 return item 1abcde