yinkaiot / app /crud.py
okeowo1014's picture
Upload 18 files
dc65e63 verified
raw
history blame
2.18 kB
# fastapi_crud/app/crud.py
from sqlalchemy.orm import Session
from . import models, schemas
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# User CRUD operations
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
def get_user_by_username(db: Session, username: str):
return db.query(models.User).filter(models.User.username == username).first()
def create_user(db: Session, user: schemas.UserCreate):
hashed_password = pwd_context.hash(user.password)
db_user = models.User(username=user.username, hashed_password=hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
# Device CRUD operations
def get_device(db: Session, device_id: int):
return db.query(models.Device).filter(models.Device.id == device_id).first()
def get_devices(db: Session, skip: int = 0, limit: int = 10):
return db.query(models.Device).offset(skip).limit(limit).all()
def create_device(db: Session, device: schemas.DeviceCreate):
db_device = models.Device(**device.dict())
db.add(db_device)
db.commit()
db.refresh(db_device)
return db_device
def update_device(db: Session, device_id: int, device: schemas.DeviceUpdate):
db_device = db.query(models.Device).filter(models.Device.id == device_id).first()
if db_device is None:
return None
for key, value in device.dict().items():
setattr(db_device, key, value)
db.commit()
db.refresh(db_device)
return db_device
def delete_device(db: Session, device_id: int):
db_device = db.query(models.Device).filter(models.Device.id == device_id).first()
if db_device is None:
return None
db.delete(db_device)
db.commit()
return db_device
def set_device_active(db: Session, device_id: int, active: bool):
db_device = db.query(models.Device).filter(models.Device.id == device_id).first()
if db_device is None:
return None
db_device.active = active
db.commit()
db.refresh(db_device)
return db_device