67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
import logging
|
|
|
|
from fastapi import Depends, FastAPI, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from . import crud, models, schemas
|
|
from.database import engine, SessionLocal
|
|
|
|
|
|
log = logging.getLogger()
|
|
|
|
models.Base.metadata.create_all(bind=engine)
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@app.get("/hello/")
|
|
def hello():
|
|
return "Hello World!"
|
|
|
|
|
|
@app.post("/users/", response_model=schemas.User)
|
|
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
|
|
existing_user = crud.read_user_by_email(db, email=user.email)
|
|
if existing_user:
|
|
raise HTTPException(status_code=400, detail="A user with this email address is already registered.")
|
|
|
|
return crud.create_user(db=db, user=user)
|
|
|
|
|
|
@app.get("/users/{id}", response_model=schemas.User)
|
|
def read_user(id: int, db: Session = Depends(get_db)):
|
|
user = crud.read_user(db=db, id=id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
|
|
return user
|
|
|
|
|
|
@app.get("/users/", response_model=list[schemas.User])
|
|
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
users = crud.read_users(db=db, skip=skip, limit=limit)
|
|
return users
|
|
|
|
|
|
@app.patch("/users/{id}", response_model=schemas.User)
|
|
def update_user(id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)):
|
|
current_user = crud.read_user(db=db, id=id)
|
|
if not current_user:
|
|
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
|
|
return crud.update_user(db=db, user=user, id=id)
|
|
|
|
|
|
@app.delete("/users/{id}", response_model=schemas.User)
|
|
def delete_user(id: int, db: Session = Depends(get_db)):
|
|
user = crud.read_user(db=db, id=id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
|
|
return crud.delete_user(db=db, id=id)
|