import quart as q from . import db BLOG_COMMENT_TEMPLATE = """

{{ comment.author }} says:

{{ comment.text }}

{{ format_ts(comment.created_at) }}

""" blueprint = q.Blueprint("blog", __name__, url_prefix="/blog") @blueprint.route("/") async def index(): posts = await db.get_posts() return await q.render_template( "blog/index.html", title="Blog", description="my little blog", posts=posts, ) @blueprint.route("/") async def see_post(id: str): post = await db.get_post(id) if post is None or not post.public: q.abort(404) return await q.render_template( "blog/post.html", title=post.title, description=post.description or "this post has no description.", post=post, ) @blueprint.route("//comments", methods=["GET"]) async def render_post_comments(id: str): TEMPLATE = f"""{{% for comment in comments|sort(attribute="created_at", reverse=True) -%}} {BLOG_COMMENT_TEMPLATE} {{%- endfor %}} {{% if comments|length == 0 %}}

no comments yet!

{{% endif %}} """ comments = await db.get_post_comments(id) return await q.render_template_string(TEMPLATE, comments=comments) @blueprint.route("//comments", methods=["POST"]) async def create_comment(id: str): form = await q.request.form author = form["author"] text = form["text"] pool = db.get_db() async with pool.acquire() as conn: await conn.execute( "INSERT INTO comments (post_id, author, text) VALUES ($1, $2, $3);", id, author, text, ) return q.Response(status=200, headers={"HX-Trigger": "newPost"})