ibs/sql_app/crud.py
HeshamTB b0dc22070e
sql_app: basic models and schemas from FastAPI docs
- Classes in models describe tables in database

	- Classes in schemas desribe pydantic models to
	read from the API.

	- database provides a connection and sessions to
	the database.

	- crud exposes the interface to the database, i.e.
	actions we can take from the application onto the
	database

Signed-off-by: HeshamTB <hishaminv@gmail.com>
2022-03-03 15:49:26 +03:00

39 lines
1.1 KiB
Python

# CRUD (Create, Read, Update, Delete) from db
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()
def get_users(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
fake_hashed_password = user.password + "notreallyhashed"
db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def get_iot_entities(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.IotEntity).offset(skip).limit(limit).all()
def create_iot_entity(db: Session, item: schemas.IotEntityCreate, user_id: int):
db_item = models.Item(**item.dict(), owner_id=user_id)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item