"""Paths related to working with database""" from sqlalchemy.orm import Session from fastapi import Depends from fastapi import Request, Response from starlette_wtf import csrf_protect from . import Paths from .. import respond from .. import sql from ..sql import crud from ..sql import schemas from ..forms import get_form from ..forms.users import AddUserForm LIMIT = 10 class TablePaths(Paths): def add_paths(self) -> None: @self.app.get('/db') def list_users( req: Request, page: int = 0, db: Session = Depends(sql.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(sql.get_db)) -> Response: form = await get_form(AddUserForm, req) if await form.validate_on_submit(): if form.pswd.data != '1234': return respond.with_text('Incorrect password') 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, )