Coverage for docs_src/dependencies/tutorial008b_an_py39.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import Annotated 1abcd

2 

3from fastapi import Depends, FastAPI, HTTPException 1abcd

4 

5app = FastAPI() 1abcd

6 

7 

8data = { 1abcd

9 "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, 

10 "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, 

11} 

12 

13 

14class OwnerError(Exception): 1abcd

15 pass 1abcd

16 

17 

18def get_username(): 1abcd

19 try: 1abcd

20 yield "Rick" 1abcd

21 except OwnerError as e: 1abcd

22 raise HTTPException(status_code=400, detail=f"Owner error: {e}") 1abcd

23 

24 

25@app.get("/items/{item_id}") 1abcd

26def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): 1abcd

27 if item_id not in data: 1abcd

28 raise HTTPException(status_code=404, detail="Item not found") 1abcd

29 item = data[item_id] 1abcd

30 if item["owner"] != username: 1abcd

31 raise OwnerError(username) 1abcd

32 return item 1abcd