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