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

87 lines
2.4 KiB
Python
Raw Normal View History

2024-02-01 00:28:17 -08:00
import logging
2024-01-31 22:39:54 -08:00
from collections import defaultdict
2024-01-28 22:14:50 -08:00
2024-01-31 22:39:54 -08:00
from wtforms_sqlalchemy.orm import model_form
2024-01-28 22:14:50 -08:00
2024-01-31 22:39:54 -08:00
from ttfrog.db.manager import db
2024-01-28 22:14:50 -08:00
2024-01-31 22:39:54 -08:00
class BaseController:
model = None
def __init__(self, request):
self.request = request
self.attrs = defaultdict(str)
2024-02-01 00:28:17 -08:00
self.record = None
self.model_form = None
2024-01-31 22:39:54 -08:00
self.config = {
'static_url': '/static',
'project_name': 'TTFROG'
}
2024-02-01 00:28:17 -08:00
self.configure()
self.configure_for_model()
def configure_for_model(self):
if not self.model:
return
if not self.model_form:
self.model_form = model_form(self.model, db_session=db.session)
if not self.record:
self.record = self.load_from_slug() or self.load_from_id()
if 'all_records' not in self.attrs:
self.attrs['all_records'] = db.query(self.model).all()
2024-01-31 22:39:54 -08:00
def configure(self):
2024-02-01 00:28:17 -08:00
pass
def load_from_slug(self):
if not self.model:
return
parts = self.request.matchdict.get('uri', '').split('/')
if not parts:
return
try:
return db.query(self.model).filter(self.model.slug == parts[0])[0]
except IndexError:
logging.warning(f"Could not load record with slug {parts[0]}")
2024-01-31 22:39:54 -08:00
def load_from_id(self):
2024-02-01 00:28:17 -08:00
post_id = self.request.POST.get('id', None)
if not post_id:
2024-01-31 22:39:54 -08:00
return
2024-02-01 00:28:17 -08:00
return db.query(self.model).get(post_id)
2024-01-31 22:39:54 -08:00
def form(self) -> str:
if not self.model:
2024-02-01 00:28:17 -08:00
return
2024-01-31 22:39:54 -08:00
2024-01-31 23:05:46 -08:00
if self.request.method == 'POST':
2024-02-01 00:28:17 -08:00
if not self.record:
self.record = self.model()
2024-01-31 23:05:46 -08:00
form = self.model_form(self.request.POST, obj=self.record)
if self.model.validate(form):
form.populate_obj(self.record)
2024-02-01 00:28:17 -08:00
if not self.record.id:
with db.transaction():
db.session.add(self.record)
logging.debug(f"Added {self.record = }")
2024-01-31 23:05:46 -08:00
return form
return self.model_form(obj=self.record)
2024-01-28 22:14:50 -08:00
def output(self, **kwargs) -> dict:
return dict(
2024-01-31 22:39:54 -08:00
config=self.config,
request=self.request,
2024-02-01 00:28:17 -08:00
record=self.record or '',
form=self.form() or '',
2024-01-31 22:39:54 -08:00
**self.attrs,
2024-01-28 22:14:50 -08:00
**kwargs,
)
2024-01-31 22:39:54 -08:00
def response(self):
return self.output()