-
Notifications
You must be signed in to change notification settings - Fork 1
/
crud.py
65 lines (45 loc) · 1.59 KB
/
crud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from sqlalchemy.orm import Session
from models import User
from schemas import UserCreate, ItemCreate
from sqlalchemy.exc import IntegrityError
from models import Item
from utils import get_password_hash
def create_user(db: Session, user: UserCreate):
hashed_password = get_password_hash(user.password)
db_user = User(username=user.username, email=user.email, hashed_password=hashed_password.decode('utf-8'))
try:
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
except IntegrityError:
db.rollback()
return None
def get_user(db: Session, username: str):
return db.query(User).filter(User.username == username).first()
def create_item(db: Session, item: ItemCreate):
db_item = Item(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def get_item(db: Session, item_id: int):
return db.query(Item).filter(Item.id == item_id).first()
def get_items(db: Session, skip: int = 0, limit: int = 10):
return db.query(Item).offset(skip).limit(limit).all()
def update_item(db: Session, item_id: int, item: ItemCreate):
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item:
for key, value in item.dict().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
return None
def delete_item(db: Session, item_id: int):
db_item = db.query(Item).filter(Item.id == item_id).first()
if db_item:
db.delete(db_item)
db.commit()
return db_item
return None