Advanced · Web & APIs · Packages: standard library only
Project 29: Static Site Generator
Build a tiny static site generator: it parses pages with header fields, converts mini Markdown to HTML, fills a template with navigation, writes a site folder and checks links.
What you will learn
- Parse a simple front matter header from text
- Convert headings, lists, quotes and inline styles to HTML with re
- Fill an HTML template using str.format
- Create folders and files with os and shutil
- Verify that all internal links point to real files
Prerequisites
- Strings and string methods
- Dictionaries, lists and sorting
- Functions and nested functions
- The re module (regular expressions)
- File and folder handling (os, shutil)
- Basic HTML tags
Packages and installation
Packages: standard library only.
standard library only (no pip install needed)
Project structure
sitegen/
main.py
site/ (created when you run it)
index.html
about.html
blog.html
contact.html
style.cssStep-by-step build
- Define the sample pages. PAGES is a dictionary of slug to text. Each text has header lines (title, order), a --- line, then Markdown. In a real project these would be .md files read from disk.
- Write the HTML template. TEMPLATE has placeholders such as {title}, {nav} and {body}. Every page uses the same template, so the layout stays consistent.
- Parse the header. parse_page() splits the text at the --- line and turns 'key: value' lines into a dictionary.
- Convert inline Markdown. inline() escapes HTML first, then replaces
code, bold, *italic* and [links](url) using regular expressions. - Convert blocks. markdown() reads line by line, collecting paragraphs and list items. flush() writes the finished block as <p>, <ul> or <ol>. Headings and quotes are written at once.
- Build the site. build_site() deletes the old output folder, sorts pages by order, renders each page with navigation, and writes the HTML and the CSS file.
- Check links and print the file list. find_broken_links() reads each built page and tests that local hrefs exist. main() prints every file with its size.
Complete source code
"""Static Site Generator: turns sample pages (front matter + mini Markdown) into HTML."""
import html
import os
import re
import shutil
# ---------- Part 1: sample content (normally these would be .md files) ----------
PAGES = {
"index": """title: Home
order: 1
---
# Welcome
This site was built by a **tiny Python script**.
Visit the [about page](about.html) or read the [blog](blog.html).
""",
"about": """title: About
order: 2
---
# About us
We write small tools in Python.
## What we use
- The standard library
- Plain text files
- A little *patience*
Use `python3 main.py` to rebuild the site.
""",
"blog": """title: Blog
order: 3
---
# Blog
## Post one
Static sites are fast and simple to host.
## Post two
Templates keep every page looking the same.
> Small steps make big projects.
""",
"contact": """title: Contact
order: 4
---
# Contact
Email: team@example.com
1. Write a message
2. Send it
3. Wait for our answer
""",
}
TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{title} - {site}</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>{nav}</nav>
<main>
{body}
</main>
<footer>{site} - page {number} of {total}</footer>
</body>
</html>
"""
CSS = """body { font-family: sans-serif; max-width: 40em; margin: 2em auto; }
nav a { margin-right: 1em; }
nav a.current { font-weight: bold; }
blockquote { color: #555; border-left: 3px solid #ccc; padding-left: 1em; }
"""
SITE_NAME = "Py Site"
OUT_DIR = "site"
# ---------- Part 2: parsing ----------
def parse_page(text):
"""Split 'key: value' header lines from the body at the '---' line."""
head, _, body = text.partition("\n---\n")
meta = {}
for line in head.splitlines():
key, _, value = line.partition(":")
meta[key.strip()] = value.strip()
return meta, body.strip()
def inline(text):
"""Convert **bold**, *italic*, `code` and [links](url) in one line."""
text = html.escape(text, quote=False)
text = re.sub(r"`([^`]+)`", r"<code>\1</code>", text)
text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
text = re.sub(r"\*(.+?)\*", r"<em>\1</em>", text)
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)
return text
def markdown(text):
"""Very small Markdown: headings, lists, quotes and paragraphs."""
out = []
block = [] # lines of the paragraph or list being collected
kind = None # "p", "ul", "ol" or None
def flush():
nonlocal block, kind
if not block:
return
if kind == "p":
out.append("<p>" + " ".join(inline(b) for b in block) + "</p>")
else:
items = "".join(f"<li>{inline(b)}</li>" for b in block)
out.append(f"<{kind}>{items}</{kind}>")
block, kind = [], None
for line in text.splitlines():
stripped = line.strip()
heading = re.match(r"(#{1,3})\s+(.*)", stripped)
bullet = re.match(r"[-*]\s+(.*)", stripped)
number = re.match(r"\d+\.\s+(.*)", stripped)
quote = re.match(r">\s?(.*)", stripped)
if not stripped:
flush()
elif heading:
flush()
level = len(heading.group(1))
out.append(f"<h{level}>{inline(heading.group(2))}</h{level}>")
elif quote:
flush()
out.append(f"<blockquote>{inline(quote.group(1))}</blockquote>")
elif bullet or number:
new_kind = "ul" if bullet else "ol"
if kind != new_kind:
flush()
kind = new_kind
block.append((bullet or number).group(1))
else:
if kind != "p":
flush()
kind = "p"
block.append(stripped)
flush()
return "\n".join(out)
# ---------- Part 3: building ----------
def build_nav(pages, current):
"""Make the menu; the current page gets a CSS class."""
links = []
for slug, meta, _ in pages:
cls = ' class="current"' if slug == current else ""
links.append(f'<a href="{slug}.html"{cls}>{html.escape(meta["title"])}</a>')
return " ".join(links)
def build_site(sources, out_dir):
"""Render every page into out_dir and return the list of files written."""
if os.path.isdir(out_dir):
shutil.rmtree(out_dir) # start clean so old files do not stay
os.makedirs(out_dir)
pages = []
for slug, text in sources.items():
meta, body = parse_page(text)
pages.append((slug, meta, body))
pages.sort(key=lambda p: int(p[1].get("order", 99)))
written = []
for number, (slug, meta, body) in enumerate(pages, start=1):
page_html = TEMPLATE.format(
title=html.escape(meta["title"]), site=SITE_NAME,
nav=build_nav(pages, slug), body=markdown(body),
number=number, total=len(pages))
path = os.path.join(out_dir, slug + ".html")
with open(path, "w", encoding="utf-8") as f:
f.write(page_html)
written.append(path)
css_path = os.path.join(out_dir, "style.css")
with open(css_path, "w", encoding="utf-8") as f:
f.write(CSS)
written.append(css_path)
return written
def find_broken_links(out_dir):
"""Check that every local href points to a file we built."""
broken = []
for name in sorted(os.listdir(out_dir)):
if not name.endswith(".html"):
continue
with open(os.path.join(out_dir, name), encoding="utf-8") as f:
for href in re.findall(r'href="([^"]+)"', f.read()):
if "://" not in href and not os.path.exists(os.path.join(out_dir, href)):
broken.append((name, href))
return broken
def main():
files = build_site(PAGES, OUT_DIR)
print(f"Built {len(files)} files in ./{OUT_DIR}/")
for path in sorted(files):
print(f" {path:<22} {os.path.getsize(path):>5} bytes")
broken = find_broken_links(OUT_DIR)
print("Broken links:", broken if broken else "none")
with open(os.path.join(OUT_DIR, "about.html"), encoding="utf-8") as f:
print("--- about.html (first 12 lines) ---")
print("".join(f.readlines()[:12]).rstrip())
if __name__ == "__main__":
main()
Code explanation
Front matter
partition('\n---\n') splits the text into two parts in one call. The header becomes metadata used for the page title and sort order.
Escaping first
html.escape runs before the other replacements, so text like <script> in a page becomes harmless. The tags we add afterwards are not escaped.
The flush() helper
A paragraph or list spans many lines, so the code collects lines in block and writes them when a blank line or a new block type appears. nonlocal lets the inner function change the outer variables.
Navigation
build_nav() is called once per page. The current page gets class="current" so CSS can bold it.
Clean builds
shutil.rmtree removes the old folder, so deleted pages do not stay in the output. Sorting the file list makes the printed output the same every time.
Link checker
A regex finds every href. Links with :// are external and skipped. The others must exist as files in the output folder.
Expected output
Built 5 files in ./site/
site/about.html 610 bytes
site/blog.html 577 bytes
site/contact.html 500 bytes
site/index.html 552 bytes
site/style.css 211 bytes
Broken links: none
--- about.html (first 12 lines) ---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>About - Py Site</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav><a href="index.html">Home</a> <a href="about.html" class="current">About</a> <a href="blog.html">Blog</a> <a href="contact.html">Contact</a></nav>
<main>
<h1>About us</h1>
<p>We write small tools in Python.</p>Common errors and solutions
Solution: A page header has no title line. Add 'title: ...' above the --- line, or use meta.get('title', slug).
Solution: os.makedirs fails if the folder exists. Remove it first with shutil.rmtree or use exist_ok=True.
Solution: The HTML was escaped twice. Escape only once, before adding your own tags.
Solution: A link has a typo. Fix the file name in the Markdown and rebuild.
Solution: The order field is not a number. Write order: 2, not order: second.
Ideas to improve the project
- Read real .md files from a content folder with pathlib
- Add a blog index page that lists posts by date
- Support images and code blocks in the Markdown converter
- Generate an RSS or sitemap.xml file
- Add a --serve option using http.server and a --watch rebuild loop
- Use a separate template file with placeholders for header and footer