Read Blog Post

This is similar to the home page function, but notice the hyperlink for each post on the home page links to /blog/UUID, for example https://www.exampleforyou.net/blog/5c6b98d8-fb67-47ac-8005-d2a6cceff6d2.

Therefore, we need a function that uses a path parameter, taking in the UUID so that the database record matching the UUID can be found, and the data passed to the template for rendering that blogpost content.

Create a new file for managing the view functions relating to Blog Posts:

web/views/blog_views.pypython
import uuid

from fastapi import APIRouter, status, Request, Depends
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session

from api.blog_apis import get_blogpost_by_id_api
from db.db import get_session_db

router = APIRouter()

templates = Jinja2Templates('web/templates')

@router.get('/blog/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):

    post = get_blogpost_by_id_api(id=id, session=session)

    context = {
        "page": "blog",
        "post": post
    }

    return templates.TemplateResponse(request, 'blogpost.html', {'context': context})

If there’s no post with that id, get_blogpost_by_id_api raises its 404 HTTPException, which works just as well from a view. For now you’ll see the JSON error, and the Custom 404 Page section turns it into a proper page.

We’ll also need to add the template blogpost.html for rendering blog posts:

web/templates/blogpost.htmljinja
{% extends "_base.html" %}

{% block content %}

 <!-- Page Header -->
 <header class="intro-header" style="background-image: url('{{ context.post.cover_image }}')">
     <div class="container">
         <div class="row">
             <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                 <div class="post-heading">
                     <h1>{{ context.post.title }}</h1>
                     <h2 class="subheading">{{ context.post.teaser }}</h2>
                     <span class="meta">Posted on {{ context.post.created_date.strftime('%d %B %Y') }}</span>
                 </div>
             </div>
         </div>
     </div>
 </header>

 <!-- Post Content -->
 <article>
     <div class="container">
         <div class="row">
             <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                 {{ context.post.content }}
             </div>
         </div>
     </div>
 </article>

{% endblock %}

The header’s background image is the post’s cover_image. The sample posts from db/seed.py use /static/img/post-bg.jpg from the theme. Any image you put under web/static/img works the same way, until the Image Uploads section lets you upload them.

Jinja2 escapes variables by default, so if content contained HTML it would be displayed as text rather than run. That’s a good default. The Markdown section deals with rendering formatted content safely.

This pattern should become familiar: adding a view function and a template, and plumbing it into the main application routing. Include the router for blog views in main.py:

main.pypython
from web.views import home_view, blog_views  # UPDATED
main.pypython
def configure_routing():
    main_app.mount('/static', StaticFiles(directory='web/static'), name='static')
    main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])
    main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"])
    main_app.include_router(home_view.router, tags=["web_views"])
    main_app.include_router(blog_views.router, tags=["web_views"])  # NEW

With this in place, the links should work for each blog post on the home page and display the content, for example: