BYO Blog

Learn the foundations of FastHTML by creating your own blogging system from scratch.
Caution

This document is a work in progress.

In this tutorial we’re going to write a blog by example. Blogs are a good way to learn a web framework as they start simple yet can get surprisingly sophistated. The wikipedia definition of a blog is “an informational website consisting of discrete, often informal diary-style text entries (posts) informal diary-style text entries (posts)”, which means we need to provide these basic features:

We’ll also add in these features, so the blog can become a working site:

How to best use this tutorial

We could copy/paste every code example in sequence and have a finished blog at the end. However, it’s debatable how much we will learn through the copy/paste method. We’re not saying its impossible to learn through copy/paste, we’re just saying it’s not that of an efficient way to learn. It’s analogous to learning how to play a musical instrument or sport or video game by watching other people do it - you can learn some but its not the same as doing.

A better approach is to type out every line of code in this tutorial. This forces us to run the code through our brains, giving us actual practice in how to write FastHTML and Pythoncode and forcing us to debug our own mistakes. In some cases we’ll repeat similar tasks - a key component in achieving mastery in anything. Coming back to the instrument/sport/video game analogy, it’s exactly like actually practicing an instrument, sport, or video game. Through practice and repetition we eventually achieve mastery.

Installing FastHTML

FastHTML is just Python. Installation is often done with pip:

pip install python-fasthtml

A minimal FastHTML app

First, create the directory for our project using Python’s pathlib module:

import pathlib
pathlib.Path('blog-system').mkdir()

Now that we have our directory, let’s create a minimal FastHTML site in it.

blog-system/minimal.py
from fasthtml.common import * 

app, rt = fast_app()  

@rt("/") 
def get():
    return Titled("FastHTML", P("Let's do this!")) 

serve()

Run that with python minimal.py and you should get something like this:

python minimal.py 
Link: http://localhost:5001
INFO:     Will watch for changes in these directories: ['/Users/pydanny/projects/blog-system']
INFO:     Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
INFO:     Started reloader process [46572] using WatchFiles
INFO:     Started server process [46576]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Confirm FastHTML is running by opening your web browser to 127.0.0.1:5001. You should see something like the image below:

What about the import *?

For those worried about the use of import * rather than a PEP8-style declared namespace, understand that __all__ is defined in FastHTML’s common module. That means that only the symbols (functions, classes, and other things) the framework wants us to have will be brought into our own code via import *. Read importing from a package) for more information.

Nevertheless, if we want to use a defined namespace we can do so. Here’s an example:

from fasthtml import common as fh


app, rt = fh.fast_app()  

@rt("/") 
def get():
    return fh.Titled("FastHTML", fh.P("Let's do this!")) 

fh.serve()

Looking more closely at our app

Let’s look more closely at our application. Every line is packed with powerful features of FastHTML:

blog-system/minimal.py
1from fasthtml.common import *

2app, rt = fast_app()

3@rt("/")
4def get():
5    return Titled("FastHTML", P("Let's do this!"))

6serve()
1
The top level namespace of Fast HTML (fasthtml.common) contains everything we need from FastHTML to build applications. A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience.
2
We instantiate a FastHTML app with the fast_app() utility function. This provides a number of really useful defaults that we’ll modify or take advantage of later in the tutorial.
3
We use the rt() decorator to tell FastHTML what to return when a user visits / in their browser.
4
We connect this route to HTTP GET requests by defining a view function called get().
5
A tree of Python function calls that return all the HTML required to write a properly formed web page. You’ll soon see the power of this approach.
6
The serve() utility configures and runs FastHTML using a library called uvicorn. Any changes to this module will be reloaded into the browser.

Adding dynamic content to our minimal app

Our page is great, but we’ll make it better. Let’s add a randomized list of letters to the page. Every time the page reloads, a new list of varying length will be generated.

blog-system/random_letters.py
from fasthtml.common import *
1import string, random

app, rt = fast_app()

@rt("/")
def get():
2    letters = random.choices(string.ascii_uppercase, k=random.randint(5, 20))
3    items = [Li(c) for c in letters]
    return Titled("Random lists of letters",
4        Ul(*items)
    ) 

serve()
1
The string and random libraries are part of Python’s standard library
2
We use these libraries to generate a random length list of random letters called letters
3
Using letters as the base we use list comprehension to generate a list of Li ft display components, each with their own letter and save that to the variable items
4
Inside a call to the Ul() ft component we use Python’s *args special syntax on the items variable. Therefore *list is treated not as one argument but rather a set of them.

When this is run, it will generate something like this with a different random list of letters for each page load:

Storing the articles

The most basic component of a blog is a series of articles sorted by date authored. Rather than a database we’re going to use our computer’s harddrive to store a set of markdown files in a directory within our blog called posts. First, let’s create the directory and some test files we can use to search for:

from fastcore.utils import *
# Create some dummy posts
posts = Path("posts")
posts.mkdir(exist_ok=True)
for i in range(10): (posts/f"article_{i}.md").write_text(f"This is article {i}")

Searching for these files can be done with pathlib.

import pathlib
posts.ls()
(#10) [Path('posts/article_5.md'),Path('posts/article_1.md'),Path('posts/article_0.md'),Path('posts/article_4.md'),Path('posts/article_3.md'),Path('posts/article_7.md'),Path('posts/article_6.md'),Path('posts/article_2.md'),Path('posts/article_9.md'),Path('posts/article_8.md')]
Tip

Python’s pathlib library is quite useful and makes file search and manipulation much easier. There’s many uses for it and is compatible across operating systems.

Creating the blog home page

We now have enough tools that we can create the home page. Let’s create a new Python file and write out our simple view to list the articles in our blog.

blog-system/main.py
from fasthtml.common import *
import pathlib

app, rt = fast_app()

@rt("/")
def get():
    fnames = pathlib.Path("posts").rglob("*.md")
    items = [Li(A(fname, href=fname)) for fname in fnames]    
    return Titled("My Blog",
        Ul(*items)
    ) 

serve()
for p in posts.ls(): p.unlink()