* Update CRUD utils to use types better. * Simplify Pydantic model names, from `UserInCreate` to `UserCreate`, etc. * Upgrade packages. * Add new generic "Items" models, crud utils, endpoints, and tests. To facilitate re-using them to create new functionality. As they are simple and generic (not like Users), it's easier to copy-paste and adapt them to each use case. * Update endpoints/*path operations* to simplify code and use new utilities, prefix and tags in `include_router`. * Update testing utils. * Update linting rules, relax vulture to reduce false positives. * Update migrations to include new Items. * Update project README.md with tips about how to start with backend.
55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
from typing import List, Optional
|
|
|
|
from fastapi.encoders import jsonable_encoder
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db_models.item import Item
|
|
from app.models.item import ItemCreate, ItemUpdate
|
|
|
|
|
|
def get(db_session: Session, *, id: int) -> Optional[Item]:
|
|
return db_session.query(Item).filter(Item.id == id).first()
|
|
|
|
|
|
def get_multi(db_session: Session, *, skip=0, limit=100) -> List[Optional[Item]]:
|
|
return db_session.query(Item).offset(skip).limit(limit).all()
|
|
|
|
|
|
def get_multi_by_owner(
|
|
db_session: Session, *, owner_id: int, skip=0, limit=100
|
|
) -> List[Optional[Item]]:
|
|
return (
|
|
db_session.query(Item)
|
|
.filter(Item.owner_id == owner_id)
|
|
.offset(skip)
|
|
.limit(limit)
|
|
.all()
|
|
)
|
|
|
|
|
|
def create(db_session: Session, *, item_in: ItemCreate, owner_id: int) -> Item:
|
|
item = Item(title=item_in.title, description=item_in.description, owner_id=owner_id)
|
|
db_session.add(item)
|
|
db_session.commit()
|
|
db_session.refresh(item)
|
|
return item
|
|
|
|
|
|
def update(db_session: Session, *, item: Item, item_in: ItemUpdate) -> Item:
|
|
item_data = jsonable_encoder(item)
|
|
update_data = item_in.dict(skip_defaults=True)
|
|
for field in item_data:
|
|
if field in update_data:
|
|
setattr(item, field, update_data[field])
|
|
db_session.add(item)
|
|
db_session.commit()
|
|
db_session.refresh(item)
|
|
return item
|
|
|
|
|
|
def remove(db_session: Session, *, id: int):
|
|
item = db_session.query(Item).filter(Item.id == id).first()
|
|
db_session.delete(item)
|
|
db_session.commit()
|
|
return item
|