tabletop-frog/ttfrog/webserver/controllers/character_sheet.py

73 lines
2.1 KiB
Python
Raw Normal View History

2024-01-28 22:14:50 -08:00
import base64
import hashlib
import logging
2024-01-28 14:31:50 -08:00
from tg import expose
2024-01-28 22:14:50 -08:00
from tg import flash
from tg import validate
from tg.controllers.util import redirect
2024-01-28 14:31:50 -08:00
from ttfrog.db import db
from ttfrog.db.schema import Character
2024-01-28 22:14:50 -08:00
from ttfrog.webserver.controllers.base import BaseController
2024-01-28 14:31:50 -08:00
from ttfrog.webserver.widgets import CharacterSheet
2024-01-28 22:14:50 -08:00
class CharacterSheetController(BaseController):
2024-01-28 14:31:50 -08:00
@expose()
def _lookup(self, *parts):
2024-01-28 22:14:50 -08:00
slug = parts[0] if parts else ''
return FormController(slug), parts[1:] if len(parts) > 1 else []
2024-01-28 14:31:50 -08:00
2024-01-28 22:14:50 -08:00
class FormController(BaseController):
2024-01-28 14:31:50 -08:00
def __init__(self, slug: str):
2024-01-28 22:14:50 -08:00
super().__init__()
2024-01-28 14:31:50 -08:00
self.character = dict()
if slug:
2024-01-28 22:14:50 -08:00
self.load_from_slug(slug)
@property
def uri(self):
if self.character:
return f"/sheet/{self.character['slug']}/{self.character['name']}"
else:
return None
@property
def all_characters(self):
return [row._mapping for row in db.query(Character).all()]
2024-01-28 14:31:50 -08:00
2024-01-28 22:14:50 -08:00
def load_from_slug(self, slug) -> None:
2024-01-28 14:31:50 -08:00
self.character = db.query(Character).filter(Character.columns.slug == slug)[0]._mapping
2024-01-28 22:14:50 -08:00
def save(self, fields) -> str:
rec = dict()
if not self.character:
result, error = db.insert(Character, **fields)
if error:
return error
fields['id'] = result.inserted_primary_key[0]
fields['slug'] = db.slugify(fields)
else:
rec = dict(**self.character)
rec.update(**fields)
result, error = db.update(Character, **rec)
self.load_from_slug(rec['slug'])
if not error:
flash(f"{self.character['name']} updated!")
return redirect(self.uri)
flash(error)
2024-01-28 14:31:50 -08:00
@expose('character_sheet.html')
2024-01-28 22:14:50 -08:00
@validate(form=CharacterSheet)
def _default(self, *args, **fields):
if fields:
return self.save(fields)
return self.output(
form=CharacterSheet,
character=self.character,
all_characters=self.all_characters,
)