-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathcrud.py
More file actions
69 lines (53 loc) · 1.9 KB
/
crud.py
File metadata and controls
69 lines (53 loc) · 1.9 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
import typing as t
from . import models, schemas
from app.core.security import get_password_hash
def get_user(db: Session, user_id: int):
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
def get_user_by_email(db: Session, email: str) -> schemas.UserBase:
return db.query(models.User).filter(models.User.email == email).first()
def get_users(
db: Session, skip: int = 0, limit: int = 100
) -> t.List[schemas.UserOut]:
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
hashed_password = get_password_hash(user.password)
db_user = models.User(
first_name=user.first_name,
last_name=user.last_name,
email=user.email,
is_active=user.is_active,
is_superuser=user.is_superuser,
hashed_password=hashed_password,
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def delete_user(db: Session, user_id: int):
user = get_user(db, user_id)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
db.delete(user)
db.commit()
return user
def edit_user(
db: Session, user_id: int, user: schemas.UserEdit
) -> schemas.User:
db_user = get_user(db, user_id)
if not db_user:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
update_data = user.dict(exclude_unset=True)
if "password" in update_data:
update_data["hashed_password"] = get_password_hash(user.password)
del update_data["password"]
for key, value in update_data.items():
setattr(db_user, key, value)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user