Initial commit: simpleblog

This commit is contained in:
2026-11-14 17:05:01 +00:00
commit 31c4580da4
91 changed files with 53494 additions and 0 deletions
+871
View File
@@ -0,0 +1,871 @@
"""Public (front-end) routes."""
from flask import (
Blueprint,
abort,
current_app,
flash,
make_response,
redirect,
render_template,
request,
session,
url_for,
)
import datetime
import os
import re
import time
from xml.sax.saxutils import escape as xml_escape
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
from . import auth, notify
from .admin import _check_csrf
from .db import (
MAX_COMMENT_BODY,
_album_by_slug,
_album_media,
_all_albums,
_comment_by_id,
_comment_counts,
_comments_for,
_random_album_thumbs,
_slugify,
get_db,
parse_date,
split_tags,
)
from .markdown import render_markdown
bp = Blueprint("public", __name__)
POSTS_PER_PAGE = 10
# Draft preview links are signed and expire, so a link shared by mistake stops
# working on its own.
PREVIEW_MAX_AGE = 60 * 60 * 24 * 7
_IMG_SRC_RE = re.compile(r'<img[^>]+src=["\']([^"\']+)["\']', re.IGNORECASE)
def _utcnow():
"""Current UTC time in the DB's timestamp format (comment + schedule times)."""
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
@bp.route("/robots.txt")
def robots():
"""Serve robots.txt at the site root so search engines can crawl it.
Flask's static route only covers /static/, so this explicit route exposes
the file at /robots.txt. The Sitemap directive must be an absolute URL
(the spec rejects a relative one), so it is built from BLOG_URL when set.
"""
base = (os.environ.get("BLOG_URL") or request.url_root).rstrip("/")
body = (
"User-agent: *\n"
"Allow: /\n"
"\n"
"# Admin area and search results aren't useful to crawlers.\n"
"Disallow: /admin/\n"
"Disallow: /search\n"
"\n"
"Sitemap: %s/sitemap.xml\n" % base
)
return body, 200, {"Content-Type": "text/plain; charset=utf-8"}
@bp.route("/sitemap.xml")
def sitemap():
"""Auto-generated XML sitemap so search engines can discover every page."""
db = get_db()
now = _utcnow()
base = request.url_root.rstrip("/")
# (path, lastmod). `/about` is deliberately absent: it redirects to
# `/p/about`, which is the canonical URL already listed below.
rows = [("", None), ("/photos", None)]
rows += [
("/post/" + r["slug"], r["updated_at"])
for r in db.execute(
"SELECT slug, updated_at FROM posts "
"WHERE status = 'published' AND COALESCE(published_at, created_at) <= ? "
"ORDER BY created_at DESC",
(now,),
).fetchall()
]
rows += [
("/category/" + r["slug"], None)
for r in db.execute("SELECT slug FROM categories ORDER BY name").fetchall()
]
# Tag browsing pages, matching the links rendered on posts and cards.
rows.append(("/tags", None))
for tag in _tag_index():
rows.append(("/tag/" + tag["slug"], None))
rows += [
("/p/" + r["slug"], r["updated_at"])
for r in db.execute(
"SELECT slug, updated_at FROM pages WHERE published = 1 "
"ORDER BY position, id"
).fetchall()
]
out = ['<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
for path, lastmod in rows:
out.append(" <url>")
loc = request.url_root if path == "" else (base + path)
out.append(" <loc>%s</loc>" % xml_escape(loc))
# Real modification dates: this used to always be "today", telling
# crawlers every page changed on every crawl.
if lastmod:
out.append(" <lastmod>%s</lastmod>" % str(lastmod)[:10])
out.append(" </url>")
out.append("</urlset>")
return "\n".join(out), 200, {
"Content-Type": "application/xml",
"Cache-Control": "public, max-age=3600",
}
def _page_number():
"""Current ?page= as a positive integer (bad input falls back to 1)."""
try:
value = int(request.args.get("page", "1"))
except (TypeError, ValueError):
value = 1
return max(1, value)
def _pagination(page_number, total):
"""Template context for prev/next links, preserving query + path args."""
pages = max(1, (total + POSTS_PER_PAGE - 1) // POSTS_PER_PAGE)
def build(target):
args = request.args.to_dict()
args["page"] = target
return url_for(request.endpoint, **(request.view_args or {}), **args)
return {
"page": page_number,
"pages": pages,
"total": total,
"has_prev": page_number > 1,
"has_next": page_number < pages,
"prev_url": build(page_number - 1) if page_number > 1 else "",
"next_url": build(page_number + 1) if page_number < pages else "",
}
def _first_image(body):
"""Absolute URL of the first <img> in a post body (for social previews)."""
match = _IMG_SRC_RE.search(str(body or ""))
if not match:
return ""
src = match.group(1).strip()
if src.startswith(("http://", "https://")):
return src
return request.url_root.rstrip("/") + "/" + src.lstrip("/")
def _published(page_number=1, per_page=POSTS_PER_PAGE):
"""Published posts whose publish time has arrived (see scheduled posts)."""
db = get_db()
return db.execute(
"""
SELECT * FROM posts
WHERE status = 'published'
AND COALESCE(published_at, created_at) <= ?
ORDER BY created_at DESC, id DESC
LIMIT ? OFFSET ?
""",
(_utcnow(), per_page, (page_number - 1) * per_page),
).fetchall()
def _published_count():
db = get_db()
return db.execute(
"SELECT COUNT(*) FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ?",
(_utcnow(),),
).fetchone()[0]
def _tag_index():
"""Every tag used by live posts: [{slug, name, count}], most used first."""
db = get_db()
rows = db.execute(
"SELECT tags FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ?",
(_utcnow(),),
).fetchall()
tags = {}
for row in rows:
for name in split_tags(row["tags"]):
slug = _slugify(name)
entry = tags.setdefault(slug, {"slug": slug, "name": name, "count": 0})
entry["count"] += 1
return sorted(tags.values(), key=lambda t: (-t["count"], t["name"].lower()))
def _live_posts():
"""Every published-and-due post, newest first (used for tag filtering)."""
db = get_db()
return db.execute(
"SELECT * FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"ORDER BY created_at DESC, id DESC",
(_utcnow(),),
).fetchall()
def _tag_posts(slug):
"""Return (display name, posts) for the tag whose slug matches `slug`."""
name, matched = slug, []
for row in _live_posts():
names = {_slugify(tag): tag for tag in split_tags(row["tags"])}
if slug in names:
name = names[slug]
matched.append(row)
return name, matched
def _related_posts(post, limit=3):
"""Posts most related to `post`, using shared tags then category.
Shared tags score 2 each and a matching category scores 1, so a post with
two tags in common always outranks one that merely shares a category. Only
live posts are considered (drafts and scheduled posts never surface here).
"""
wanted = {_slugify(tag) for tag in split_tags(post["tags"])}
category = (post["category"] or "").strip().lower()
scored = []
for row in _live_posts():
if row["id"] == post["id"]:
continue
shared = len(wanted & {_slugify(tag) for tag in split_tags(row["tags"])})
same_category = bool(category) and (row["category"] or "").strip().lower() == category
if not shared and not same_category:
continue
score = shared * 2 + (1 if same_category else 0)
scored.append((score, row["created_at"] or "", row))
scored.sort(key=lambda item: (item[0], item[1]), reverse=True)
return [item[2] for item in scored[:limit]]
def _recent_other_posts(post, limit=3):
"""Fallback when a post has no tag/category neighbours: newest other posts."""
return [row for row in _live_posts() if row["id"] != post["id"]][:limit]
def _sidebar():
"""Shared sidebar data: recent posts, archive months and the tag cloud."""
db = get_db()
recent = db.execute(
"SELECT title, slug, created_at FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"ORDER BY created_at DESC, id DESC LIMIT 5",
(_utcnow(),),
).fetchall()
months = db.execute(
"SELECT substr(created_at, 1, 7) AS month FROM posts "
"WHERE status = 'published' AND COALESCE(published_at, created_at) <= ? "
"GROUP BY month ORDER BY month DESC",
(_utcnow(),),
).fetchall()
# Admin-managed link tree; empty until the first link is added, which is
# what keeps the "Links" widget off the page entirely on a fresh site.
links = db.execute(
"SELECT label, url FROM links ORDER BY position ASC, id ASC"
).fetchall()
return {"recent": recent, "months": months, "tags": _tag_index(), "links": links}
def _category_map():
db = get_db()
return {r[0]: r[1] for r in db.execute("SELECT slug, name FROM categories").fetchall()}
@bp.route("/")
def index():
page_number = _page_number()
total = _published_count()
posts = _published(page_number)
return render_template(
"home.html",
posts=posts,
category_map=_category_map(),
page="home",
pagination=_pagination(page_number, total),
sidebar=_sidebar(),
)
def _posts_in_month(month, page_number=1):
"""Return published posts whose created_at starts with `month` (e.g. '2026-11')."""
db = get_db()
return db.execute(
"SELECT * FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"AND substr(created_at, 1, 7) = ? "
"ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
(_utcnow(), month, POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE),
).fetchall()
def _month_count(month):
db = get_db()
return db.execute(
"SELECT COUNT(*) FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"AND substr(created_at, 1, 7) = ?",
(_utcnow(), month),
).fetchone()[0]
@bp.route("/archive/<month>")
def archive(month):
page_number = _page_number()
posts = _posts_in_month(month, page_number)
return render_template(
"home.html",
posts=posts,
category_map=_category_map(),
page="archive",
month=month,
pagination=_pagination(page_number, _month_count(month)),
sidebar=_sidebar(),
)
@bp.route("/post/<slug>")
def post(slug):
db = get_db()
# Scheduled posts (publish time still in the future) must not be reachable
# by URL before they go live.
row = db.execute(
"SELECT * FROM posts WHERE slug = ? AND COALESCE(published_at, created_at) <= ?",
(slug, _utcnow()),
).fetchone()
if not row:
abort(404)
cat_slug = _slugify(row["category"])
# Approved comments for this post are rendered by the shared comments partial;
# `enabled`, `logged_in` and `csrf_token` come from expose_helpers().
comments = _comments_for("post", row["id"])
# Tag/category matches first; on a small blog with no overlap, fall back to
# the newest posts (labelled differently) instead of an empty section.
related = _related_posts(row)
related_fallback = False
if not related:
related = _recent_other_posts(row)
related_fallback = bool(related)
return render_template(
"post.html",
post=row,
category_map=_category_map(),
cat_slug=cat_slug,
page="post",
object_type="post",
slug=slug,
comments=comments,
comment_count=len(comments),
og_image=_first_image(row["body"]),
related=related,
related_fallback=related_fallback,
preview=False,
)
@bp.route("/preview/<int:pid>/<token>")
def preview(pid, token):
"""Signed preview of a draft or scheduled post (noindex, never public).
The URL carries an itsdangerous token bound to the post id, so drafts are
not reachable by guessing an id and shared links expire after a week.
"""
serializer = URLSafeTimedSerializer(
current_app.config["SECRET_KEY"], salt="post-preview"
)
try:
signed_pid = int(serializer.loads(token, max_age=PREVIEW_MAX_AGE))
except (BadSignature, SignatureExpired, TypeError, ValueError):
abort(404)
if signed_pid != pid:
abort(404)
row = get_db().execute("SELECT * FROM posts WHERE id = ?", (pid,)).fetchone()
if not row:
abort(404)
related = _related_posts(row)
related_fallback = False
if not related:
related = _recent_other_posts(row)
related_fallback = bool(related)
response = make_response(
render_template(
"post.html",
post=row,
category_map=_category_map(),
cat_slug=_slugify(row["category"]),
page="post",
object_type="post",
slug=row["slug"],
comments=[],
comment_count=0,
# Drafts must not accept comments: the public comment route would
# otherwise happily attach one to an unpublished post.
comments_enabled=False,
og_image=_first_image(row["body"]),
related=related,
related_fallback=related_fallback,
preview=True,
)
)
response.headers["X-Robots-Tag"] = "noindex, nofollow"
response.headers["Cache-Control"] = "no-store, private"
return response
@bp.route("/category/<slug>")
def category(slug):
db = get_db()
cat = db.execute(
"SELECT name FROM categories WHERE slug = ?", (slug,)
).fetchone()
if not cat:
abort(404)
# Posts store the category's display name, not its slug, so match the name
# (and tolerate a slug stored by an import). This used to fall back to
# "every published post" whenever the strings didn't match — so any category
# whose name differed from its slug showed the whole blog, and an empty
# category did too.
page_number = _page_number()
where = (
"status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"AND (lower(category) = lower(?) OR lower(category) = lower(?))"
)
params = (_utcnow(), cat["name"], slug)
total = db.execute(
"SELECT COUNT(*) FROM posts WHERE " + where, params
).fetchone()[0]
posts = db.execute(
"SELECT * FROM posts WHERE " + where +
" ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
params + (POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE),
).fetchall()
return render_template(
"home.html",
posts=posts,
category_map=_category_map(),
page="category",
category_name=cat["name"],
pagination=_pagination(page_number, total),
sidebar=_sidebar(),
)
@bp.route("/tags")
def tags():
"""Browse every tag, most-used first."""
return render_template("tags.html", tag_index=_tag_index(), page="tags")
@bp.route("/tag/<slug>")
def tag(slug):
name, matched = _tag_posts(slug)
if not matched:
abort(404)
page_number = _page_number()
start = (page_number - 1) * POSTS_PER_PAGE
return render_template(
"home.html",
posts=matched[start:start + POSTS_PER_PAGE],
category_map=_category_map(),
page="tag",
tag_name=name,
tag_slug=slug,
pagination=_pagination(page_number, len(matched)),
sidebar=_sidebar(),
)
@bp.route("/tag/<slug>/feed.xml")
def tag_feed(slug):
name, matched = _tag_posts(slug)
if not matched:
abort(404)
title = "%s — %s" % (_site_title(), name)
return _atom(matched[:FEED_LIMIT], title, url_for("public.tag_feed", slug=slug)), 200, {
"Content-Type": "application/atom+xml; charset=utf-8",
"Cache-Control": "public, max-age=600",
}
def _page_by_slug(slug):
db = get_db()
row = db.execute("SELECT * FROM pages WHERE slug = ?", (slug,)).fetchone()
if not row or int(row["published"]) != 1:
abort(404)
return row
@bp.route("/about")
def about():
# Backwards-compatible alias: the About content now lives in the pages table,
# so redirect here to its canonical /p/about URL.
return redirect(url_for("public.page", slug="about"))
@bp.route("/p/<slug>")
def page(slug):
row = _page_by_slug(slug)
# Approved comments for this page are rendered by the shared comments partial.
comments = _comments_for("page", row["id"])
return render_template(
"page.html",
page=row,
page_name="page",
object_type="page",
slug=slug,
comments=comments,
comment_count=len(comments),
)
@bp.route("/photos")
def photos_index():
"""List every album so visitors can browse them (dynamically from the DB)."""
albums = _all_albums()
album_counts = {a["id"]: len(_album_media(a["id"])) for a in albums}
album_thumbs = _random_album_thumbs()
return render_template(
"public/albums.html",
albums=albums,
album_counts=album_counts,
album_thumbs=album_thumbs,
)
@bp.route("/photos/<slug>")
def photos(slug):
album = _album_by_slug(slug)
if not album:
abort(404)
rows = _album_media(album["id"])
return render_template("photos.html", album=album, media=rows)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
# --------------------------------------------------------------------------- #
# Comments (public submission)
# --------------------------------------------------------------------------- #
# A lightweight, human-moderated commenting system. Every public submission is
# stored as 'pending' and only reaches visitors once an admin approves it, so a
# single bad-faith post can't spam the site. See blog/admin.py for moderation.
# --------------------------------------------------------------------------- #
COMMENT_RATE_LIMIT = 5 # max submissions per client per window
COMMENT_RATE_WINDOW = 60 # seconds
COMMENT_MIN_SECONDS = 3 # a human needs at least this long to write a comment
def _validate_comment_input():
"""Validate + sanitise the raw submit fields. Returns a cleaned dict,
or None if the input is invalid (caller flashes an error)."""
author = (request.form.get("author") or "").strip()
email = (request.form.get("email") or "").strip()
body = (request.form.get("body") or "").strip()
if not author:
return None
if len(author) > 100:
return None
if email and not EMAIL_RE.match(email):
return None
# Body must be non-trivial: reject empty/whitespace and near-empty filler.
words = body.split()
if len(words) < 3:
return None
if len(body) > MAX_COMMENT_BODY:
return None
return {"author": author, "email": email, "body": body}
def _throttle_ok():
"""Allow at most COMMENT_RATE_LIMIT submissions per client per window.
The counter lives in the database: the previous version stored it in the
signed session cookie, so clearing cookies (or changing the submitted
email address) reset the limit.
"""
now = time.time()
key = request.remote_addr or "unknown"
db = get_db()
db.execute(
"DELETE FROM comment_attempts WHERE ts < ?", (now - COMMENT_RATE_WINDOW,)
)
recent = db.execute(
"SELECT COUNT(*) FROM comment_attempts WHERE key = ? AND ts >= ?",
(key, now - COMMENT_RATE_WINDOW),
).fetchone()[0]
if recent >= COMMENT_RATE_LIMIT:
db.commit()
return False
db.execute("INSERT INTO comment_attempts (key, ts) VALUES (?, ?)", (key, now))
db.commit()
return True
def _submit_comment(object_type, slug):
"""Shared handler for the post/page comment forms.
Validates CSRF, object existence and input; stores the comment as 'pending'
(awaiting admin approval). Redirects back to the object's public page.
"""
if not _check_csrf():
flash("Invalid request.", "error")
abort(400)
# Optional site-wide comments toggle.
enabled = get_db().execute(
"SELECT value FROM settings WHERE key = 'comments_enabled'"
).fetchone()
if enabled is None or int(enabled[0]) != 1:
return redirect(url_for("public.page_comment", object_type=object_type, slug=slug))
# The comment must attach to a real post/page.
if object_type == "post":
row = get_db().execute("SELECT * FROM posts WHERE slug = ?", (slug,)).fetchone()
target_route = url_for("public.post", slug=slug)
else:
row = get_db().execute("SELECT * FROM pages WHERE slug = ?", (slug,)).fetchone()
target_route = url_for("public.page", slug=slug)
if not row:
abort(404)
# --- Bot traps -------------------------------------------------------
# `website` is a hidden field no human ever fills in: a value means an
# automated submission, so drop it silently (no error, no hint).
if (request.form.get("website") or "").strip():
return redirect(target_route)
# The form carries its render timestamp; submissions arriving faster than a
# person can type — or replayed from a day-old page — are rejected.
try:
rendered_at = float(request.form.get("ts") or 0)
except (TypeError, ValueError):
rendered_at = 0.0
elapsed = time.time() - rendered_at
if rendered_at and (elapsed < COMMENT_MIN_SECONDS or elapsed > 86400):
flash("Please take a moment to write your comment.", "error")
return redirect(target_route)
validated = _validate_comment_input()
if validated is None:
flash("Please fill in your name and a genuine comment.", "error")
return redirect(target_route)
if not _throttle_ok():
flash("Please wait a moment before submitting another comment.", "error")
return redirect(target_route)
now = _utcnow()
db = get_db()
db.execute(
"INSERT INTO comments (object_type, object_id, author, email, body, status, created_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)",
(object_type, row["id"], validated["author"], validated["email"],
validated["body"], now, now),
)
db.commit()
# Alert the admin by email and/or push (best-effort; unconfigured channels
# are a no-op). Runs on daemon threads, so a slow server never delays the
# visitor.
notify.notify_new_comment(
comment_author=validated["author"],
comment_body=validated["body"],
comment_email=validated["email"],
target_title=row["title"],
target_url=url_for(
"public.post" if object_type == "post" else "public.page",
slug=slug,
_external=True,
),
moderation_url=url_for("admin.comments", _external=True),
)
flash("Thanks! Your comment is awaiting moderation and will appear shortly.", "success")
return redirect(target_route)
@bp.route("/post/<slug>/comment", methods=["POST"])
def post_comment(slug):
return _submit_comment("post", slug)
@bp.route("/p/<slug>/comment", methods=["POST"])
def page_comment(slug):
return _submit_comment("page", slug)
@bp.route("/comment/<int:cid>/delete", methods=["POST"])
def public_comment_delete(cid):
"""Let a logged-in user delete their own public comment."""
if not _check_csrf():
flash("Invalid request.", "error")
abort(400)
db = get_db()
row = _comment_by_id(cid)
if not row:
abort(404)
if not auth.is_logged_in():
flash("You must be signed in to delete your comment.", "error")
return redirect(request.referrer or "/")
if row["author"] != session.get("username"):
flash("You can only delete your own comments.", "error")
return redirect(request.referrer or "/")
db.execute("DELETE FROM comments WHERE id=?", (cid,))
db.commit()
flash("Your comment was deleted.", "success")
return redirect(request.referrer or "/")
# --- Search -------------------------------------------------------------------
# Lightweight substring search over published posts (title / excerpt / body).
# Replaces the earlier SearXNG-backed route with a self-contained SQL LIKE query
# so results never depend on an external search service.
@bp.route("/search")
def search():
q = request.args.get("q", "").strip()
db = get_db()
page_number = _page_number()
posts, total = [], 0
if q:
# Escape the LIKE wildcards so "%" and "_" search for themselves
# instead of matching everything.
escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
like = "%" + escaped + "%"
# Scheduled posts are published-but-future; like every other listing
# they must stay out of results until their publish time arrives.
where = (
"status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"AND (title LIKE ? ESCAPE '\\' "
"OR excerpt LIKE ? ESCAPE '\\' "
"OR body LIKE ? ESCAPE '\\')"
)
params = (_utcnow(), like, like, like)
total = db.execute(
"SELECT COUNT(*) FROM posts WHERE " + where, params
).fetchone()[0]
posts = db.execute(
"SELECT * FROM posts WHERE " + where +
" ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
params + (POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE),
).fetchall()
return render_template(
"search.html",
query=q,
posts=posts,
category_map={},
pagination=_pagination(page_number, total),
)
# --------------------------------------------------------------------------- #
# Atom feed
# --------------------------------------------------------------------------- #
FEED_LIMIT = 20
def _site_title():
row = get_db().execute(
"SELECT value FROM settings WHERE key = 'site_title'"
).fetchone()
return (row[0] if row else "") or "Blog"
def _rfc3339(value):
"""Stored UTC timestamp -> RFC 3339 ("YYYY-MM-DD HH:MM:SS" -> "...T...Z")."""
if not value:
return ""
return str(value).replace(" ", "T") + "Z"
def _atom(posts, title, feed_path):
"""Render an Atom 1.0 document for `posts` (shared by both feed routes)."""
base = request.url_root.rstrip("/")
self_url = base + feed_path
updated = (
_rfc3339(posts[0]["updated_at"] or posts[0]["created_at"])
if posts else _rfc3339(_utcnow())
)
out = [
'<?xml version="1.0" encoding="utf-8"?>',
'<feed xmlns="http://www.w3.org/2005/Atom">',
" <title>%s</title>" % xml_escape(title),
' <link rel="alternate" type="text/html" href="%s"/>' % xml_escape(base + "/"),
' <link rel="self" type="application/atom+xml" href="%s"/>' % xml_escape(self_url),
" <id>%s</id>" % xml_escape(self_url),
" <updated>%s</updated>" % updated,
" <generator>Simple Blog</generator>",
" <author><name>%s</name></author>" % xml_escape(_site_title()),
]
for p in posts:
url = base + url_for("public.post", slug=p["slug"])
out += [
" <entry>",
" <title>%s</title>" % xml_escape(p["title"] or ""),
' <link rel="alternate" type="text/html" href="%s"/>' % xml_escape(url),
" <id>%s</id>" % xml_escape(url),
" <published>%s</published>" % _rfc3339(p["created_at"]),
" <updated>%s</updated>" % _rfc3339(p["updated_at"] or p["created_at"]),
" <author><name>%s</name></author>" % xml_escape(p["author"] or "editor"),
]
if p["category"]:
out.append(' <category term="%s"/>' % xml_escape(p["category"]))
out += [
' <content type="html">%s</content>'
% xml_escape(str(render_markdown(p["body"]))),
" </entry>",
]
out.append("</feed>")
return "\n".join(out)
@bp.route("/feed.xml")
def feed():
"""Site-wide Atom feed of the most recent posts."""
posts = get_db().execute(
"SELECT * FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"ORDER BY created_at DESC LIMIT ?",
(_utcnow(), FEED_LIMIT),
).fetchall()
return _atom(posts, _site_title(), url_for("public.feed")), 200, {
"Content-Type": "application/atom+xml; charset=utf-8",
"Cache-Control": "public, max-age=600",
}
@bp.route("/category/<slug>/feed.xml")
def category_feed(slug):
"""Atom feed for a single category."""
cat = get_db().execute(
"SELECT name FROM categories WHERE slug = ?", (slug,)
).fetchone()
if not cat:
abort(404)
posts = get_db().execute(
"SELECT * FROM posts WHERE status = 'published' "
"AND COALESCE(published_at, created_at) <= ? "
"AND (lower(category) = lower(?) OR lower(category) = lower(?)) "
"ORDER BY created_at DESC LIMIT ?",
(_utcnow(), cat["name"], slug, FEED_LIMIT),
).fetchall()
title = "%s — %s" % (_site_title(), cat["name"])
return _atom(posts, title, url_for("public.category_feed", slug=slug)), 200, {
"Content-Type": "application/atom+xml; charset=utf-8",
"Cache-Control": "public, max-age=600",
}