Coverage for docs_src/sql_databases/sql_app_py310/alt_main.py: 100%
39 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, Request, Response 1abc
2from sqlalchemy.orm import Session 1abc
4from . import crud, models, schemas 1abc
5from .database import SessionLocal, engine 1abc
7models.Base.metadata.create_all(bind=engine) 1abc
9app = FastAPI() 1abc
12@app.middleware("http") 1abc
13async def db_session_middleware(request: Request, call_next): 1abc
14 response = Response("Internal server error", status_code=500) 1abc
15 try: 1abc
16 request.state.db = SessionLocal() 1abc
17 response = await call_next(request) 1abc
18 finally:
19 request.state.db.close() 1abc
20 return response 1abc
23# Dependency
24def get_db(request: Request): 1abc
25 return request.state.db 1abc
28@app.post("/users/", response_model=schemas.User) 1abc
29def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): 1abc
30 db_user = crud.get_user_by_email(db, email=user.email) 1abc
31 if db_user: 1abc
32 raise HTTPException(status_code=400, detail="Email already registered") 1abc
33 return crud.create_user(db=db, user=user) 1abc
36@app.get("/users/", response_model=list[schemas.User]) 1abc
37def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abc
38 users = crud.get_users(db, skip=skip, limit=limit) 1abc
39 return users 1abc
42@app.get("/users/{user_id}", response_model=schemas.User) 1abc
43def read_user(user_id: int, db: Session = Depends(get_db)): 1abc
44 db_user = crud.get_user(db, user_id=user_id) 1abc
45 if db_user is None: 1abc
46 raise HTTPException(status_code=404, detail="User not found") 1abc
47 return db_user 1abc
50@app.post("/users/{user_id}/items/", response_model=schemas.Item) 1abc
51def create_item_for_user( 1abc
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) 1abc
57@app.get("/items/", response_model=list[schemas.Item]) 1abc
58def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abc
59 items = crud.get_items(db, skip=skip, limit=limit) 1abc
60 return items 1abc