tmpl-fastapi/app/sql/crud.py

43 lines
822 B
Python
Raw Permalink Normal View History

2023-02-19 16:49:44 +03:00
from typing import Optional, List
2023-02-20 11:09:43 +03:00
2023-02-19 16:49:44 +03:00
from sqlalchemy.orm import Session
from . import models
from . import schemas
2023-02-27 18:05:04 +03:00
# SELECT * from users LIMIT 1
2023-02-19 16:49:44 +03: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 18:05:04 +03:00
# SELECT * from users
2023-02-19 16:49:44 +03:00
def get_users(
db: Session,
skip: int = 0,
2023-02-20 11:09:43 +03:00
limit: int = 100) -> List[models.User]:
2023-02-19 16:49:44 +03:00
return db \
.query(models.User) \
.offset(skip) \
.limit(limit) \
.all()
2023-02-27 18:05:04 +03:00
# INSERT INTO users
2023-02-19 16:49:44 +03:00
def create_user(
db: Session,
2023-02-20 11:09:43 +03:00
user: schemas.UserCreate) -> models.User:
2023-02-19 16:49:44 +03:00
user_model = models.User(**user.dict())
db.add(user_model)
db.commit()
db.refresh(user_model)
return user_model