Spaces:
Sleeping
A newer version of the Streamlit SDK is available:
1.46.1
BYO Blog
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:
- A list of articles
- A means to create/edit/delete the articles
- An attractive but accessible layout
We’ll also add in these features, so the blog can become a working site:
- RSS feed
- Pages independent of the list of articles (about and contact come to mind)
- Import and Export of articles
- Tagging and categorization of data
- Deployment
- Ability to scale for large volumes of readers
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 viaimport *
. 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
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get():
return Titled("FastHTML", P("Let's do this!"))
serve()
Line 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.
Line 3
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.
Line 5
We use the rt()
decorator to tell FastHTML what to return when a user
visits /
in their browser.
Line 6
We connect this route to HTTP GET requests by defining a view function
called get()
.
Line 7
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.
Line 9
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 *
import string, random
app, rt = fast_app()
@rt("/")
def get():
letters = random.choices(string.ascii_uppercase, k=random.randint(5, 20))
items = [Li(c) for c in letters]
return Titled("Random lists of letters",
Ul(*items)
)
serve()
Line 2
The string
and random
libraries are part of Python’s standard
library
Line 8
We use these libraries to generate a random length list of random
letters called letters
Line 9
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
Line 11
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()