tmpl-fastapi/app/paths/table.py

71 lines
1.8 KiB
Python
Raw Normal View History

"""Paths related to working with database"""
2023-02-20 11:09:43 +03:00
from sqlalchemy.orm import Session
from fastapi import Depends
from fastapi import Request, Response
from starlette_wtf import csrf_protect
from . import Paths
2023-02-20 11:09:43 +03:00
from .. import respond
from ..sql import db
from ..sql import crud
from ..sql import schemas
from ..forms import get_form
2023-02-20 11:09:43 +03:00
from ..forms.users import AddUserForm
LIMIT = 10
class TablePaths(Paths):
2023-02-20 11:09:43 +03:00
def add_paths(self) -> None:
@self.app.get('/db')
def list_users(
req: Request,
page: int = 0,
db: Session = Depends(db.get_db)) -> Response:
return respond.with_tmpl(
'table.html',
request=req,
rows=crud.get_users(
db=db,
skip=(page * LIMIT),
limit=LIMIT,
),
)
@self.app.get('/add')
@self.app.post('/add')
@csrf_protect
async def add_form(
req: Request,
db_s: Session = Depends(db.get_db)) -> Response:
form = await get_form(AddUserForm, req)
2023-02-20 11:09:43 +03:00
if await form.validate_on_submit():
if form.pswd.data != '1234':
return respond.with_text('Incorrect password')
2023-02-27 18:05:57 +03:00
2023-02-20 11:09:43 +03:00
crud.create_user(
db=db_s,
user=schemas.UserCreate(
email=form.email.data,
name=form.name.data,
age=form.age.data or 0,
),
)
return respond.with_redirect('/db')
return respond.with_tmpl(
'admin.html',
request=req,
form=form,
)