Coverage for docs_src/sql_databases/sql_app_py39/alt_main.py: 100%

39 statements  

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

1from fastapi import Depends, FastAPI, HTTPException, Request, Response 1abcd

2from sqlalchemy.orm import Session 1abcd

3 

4from . import crud, models, schemas 1abcd

5from .database import SessionLocal, engine 1abcd

6 

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

8 

9app = FastAPI() 1abcd

10 

11 

12@app.middleware("http") 1abcd

13async def db_session_middleware(request: Request, call_next): 1abcd

14 response = Response("Internal server error", status_code=500) 1abcd

15 try: 1abcd

16 request.state.db = SessionLocal() 1abcd

17 response = await call_next(request) 1abcd

18 finally: 

19 request.state.db.close() 1abcd

20 return response 1abcd

21 

22 

23# Dependency 

24def get_db(request: Request): 1abcd

25 return request.state.db 1abcd

26 

27 

28@app.post("/users/", response_model=schemas.User) 1abcd

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

30 db_user = crud.get_user_by_email(db, email=user.email) 1abcd

31 if db_user: 1abcd

32 raise HTTPException(status_code=400, detail="Email already registered") 1abcd

33 return crud.create_user(db=db, user=user) 1abcd

34 

35 

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

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

38 users = crud.get_users(db, skip=skip, limit=limit) 1abcd

39 return users 1abcd

40 

41 

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

43def read_user(user_id: int, db: Session = Depends(get_db)): 1abcd

44 db_user = crud.get_user(db, user_id=user_id) 1abcd

45 if db_user is None: 1abcd

46 raise HTTPException(status_code=404, detail="User not found") 1abcd

47 return db_user 1abcd

48 

49 

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

51def create_item_for_user( 1abcd

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

53): 

54 return crud.create_user_item(db=db, item=item, user_id=user_id) 1abcd

55 

56 

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

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

59 items = crud.get_items(db, skip=skip, limit=limit) 1abcd

60 return items 1abcd