Coverage for docs_src/sql_databases/sql_app_py310/main.py: 100%

34 statements  

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

1from fastapi import Depends, FastAPI, HTTPException 1abc

2from sqlalchemy.orm import Session 1abc

3 

4from . import crud, models, schemas 1abc

5from .database import SessionLocal, engine 1abc

6 

7models.Base.metadata.create_all(bind=engine) 1abc

8 

9app = FastAPI() 1abc

10 

11 

12# Dependency 

13def get_db(): 1abc

14 db = SessionLocal() 1abc

15 try: 1abc

16 yield db 1abc

17 finally: 

18 db.close() 1abc

19 

20 

21@app.post("/users/", response_model=schemas.User) 1abc

22def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): 1abc

23 db_user = crud.get_user_by_email(db, email=user.email) 1abc

24 if db_user: 1abc

25 raise HTTPException(status_code=400, detail="Email already registered") 1abc

26 return crud.create_user(db=db, user=user) 1abc

27 

28 

29@app.get("/users/", response_model=list[schemas.User]) 1abc

30def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abc

31 users = crud.get_users(db, skip=skip, limit=limit) 1abc

32 return users 1abc

33 

34 

35@app.get("/users/{user_id}", response_model=schemas.User) 1abc

36def read_user(user_id: int, db: Session = Depends(get_db)): 1abc

37 db_user = crud.get_user(db, user_id=user_id) 1abc

38 if db_user is None: 1abc

39 raise HTTPException(status_code=404, detail="User not found") 1abc

40 return db_user 1abc

41 

42 

43@app.post("/users/{user_id}/items/", response_model=schemas.Item) 1abc

44def create_item_for_user( 1abc

45 user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) 

46): 

47 return crud.create_user_item(db=db, item=item, user_id=user_id) 1abc

48 

49 

50@app.get("/items/", response_model=list[schemas.Item]) 1abc

51def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abc

52 items = crud.get_items(db, skip=skip, limit=limit) 1abc

53 return items 1abc