35 lines
940 B
Python
35 lines
940 B
Python
"""
|
|
utils.converter: Custom URL converters to match patterns in @app.route()
|
|
"""
|
|
|
|
from werkzeug.routing import BaseConverter
|
|
from app.models.forum import Forum
|
|
import re
|
|
|
|
class ForumConverter(BaseConverter):
|
|
|
|
def to_python(self, url):
|
|
f = Forum.query.filter_by(url=url).first()
|
|
if f is None:
|
|
raise Exception(f"ForumConverter: no forum with url {value}")
|
|
return f
|
|
|
|
def to_url(self, forum):
|
|
return forum.url
|
|
|
|
class TopicSlugConverter(BaseConverter):
|
|
|
|
def to_python(self, url):
|
|
"""Convert an URL pattern to a Python object, or raise an exception."""
|
|
m = re.fullmatch(r'(\d+)(?:-[\w-]*)?', url)
|
|
if m is None:
|
|
raise Exception(f"TopicSlugConverter: conversation failed")
|
|
|
|
return int(m[1], 10)
|
|
|
|
def to_url(self, topic_id):
|
|
return str(topic_id)
|
|
|
|
# Export only the converter classes
|
|
__all__ = "ForumConverter TopicSlugConverter".split()
|