yinkaiot / app /routers /device.py
okeowo1014's picture
Upload 18 files
dc65e63 verified
raw
history blame
2.83 kB
# fastapi_crud/app/routers/device.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app import crud, schemas, database, auth
router = APIRouter()
@router.post("/devices/", response_model=schemas.Device)
def create_device(device: schemas.DeviceCreate, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
return crud.create_device(db=db, device=device)
@router.get("/devices/", response_model=List[schemas.Device])
def read_devices(skip: int = 0, limit: int = 10, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
devices = crud.get_devices(db, skip=skip, limit=limit)
return devices
@router.get("/devices/{device_id}", response_model=schemas.Device)
def read_device(device_id: int, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
db_device = crud.get_device(db, device_id=device_id)
if db_device is None:
raise HTTPException(status_code=404, detail="Device not found")
return db_device
@router.post("/devices/{device_id}/update", response_model=schemas.Device)
def update_device(device_id: int, device: schemas.DeviceUpdate, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
db_device = crud.update_device(db, device_id=device_id, device=device)
if db_device is None:
raise HTTPException(status_code=404, detail="Device not found")
return db_device
@router.delete("/devices/{device_id}", response_model=schemas.Device)
def delete_device(device_id: int, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
db_device = crud.delete_device(db, device_id=device_id)
if db_device is None:
raise HTTPException(status_code=404, detail="Device not found")
return db_device
@router.post("/devices/{device_id}/on", response_model=schemas.Device)
def set_device_on(device_id: int, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
db_device = crud.set_device_active(db, device_id=device_id, active=True)
if db_device is None:
raise HTTPException(status_code=404, detail="Device not found")
return db_device
@router.post("/devices/{device_id}/off", response_model=schemas.Device)
def set_device_off(device_id: int, db: Session = Depends(database.get_db), current_user: schemas.User = Depends(auth.get_current_user)):
db_device = crud.set_device_active(db, device_id=device_id, active=False)
if db_device is None:
raise HTTPException(status_code=404, detail="Device not found")
return db_device