tmpl-fastapi/app/sql/crud.py

43 lines
822 B
Python
Raw Normal View History

2023-02-19 17:49:44 +04:00
from typing import Optional, List
2023-02-20 12:09:43 +04:00
2023-02-19 17:49:44 +04:00
from sqlalchemy.orm import Session
from . import models
from . import schemas
2023-02-27 19:05:04 +04:00
# SELECT * from users LIMIT 1
2023-02-19 17:49:44 +04:00
def get_user(
db: Session,
user_id: int) -> Optional[models.User]:
return db \
.query(models.User) \
.filter(models.User.id == user_id) \
.first()
2023-02-27 19:05:04 +04:00
# SELECT * from users
2023-02-19 17:49:44 +04:00
def get_users(
db: Session,
skip: int = 0,
2023-02-20 12:09:43 +04:00
limit: int = 100) -> List[models.User]:
2023-02-19 17:49:44 +04:00
return db \
.query(models.User) \
.offset(skip) \
.limit(limit) \
.all()
2023-02-27 19:05:04 +04:00
# INSERT INTO users
2023-02-19 17:49:44 +04:00
def create_user(
db: Session,
2023-02-20 12:09:43 +04:00
user: schemas.UserCreate) -> models.User:
2023-02-19 17:49:44 +04:00
user_model = models.User(**user.dict())
db.add(user_model)
db.commit()
db.refresh(user_model)
return user_model