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