Files
simpleblog/blog/wxr_export.py
T
2026-11-14 17:05:01 +00:00

169 lines
6.6 KiB
Python

"""Generate a WordPress eXtended RSS (WXR) export from this blog's data.
The output is a standard WXR 1.2 feed — the same format WordPress's own
"Import" tool reads. Posts become <item> elements; categories and tags are
expressed as <category domain="category"> / domain="post_tag">; comments appear
as <wfw:comment> blocks inside their post's item.
Only published posts are exported (option a: text only, images left in place —
their URLs keep pointing at the source host). Pure logic, stdlib only, so it can
be unit-tested without an HTTP server or database.
"""
import re
from datetime import datetime, timezone
# Characters that are not legal in XML 1.0: a body pasted from another system
# could contain them and make the exported file unparseable.
_INVALID_XML = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f]")
# WXR namespaces. The order here controls prefix order in the emitted output.
NS = [
("excerpt", "http://wordpress.org/export/1.2/excerpt/"),
("content", "http://purl.org/rss/1.0/modules/content/"),
("wfw", "http://wellformedweb.org/CommentAPI/"),
("dc", "http://purl.org/dc/elements/1.1/"),
("wp", "http://wordpress.com/export/1.2/"),
("slash", "http://slashworks.org/rss/1.0/"),
]
def _xml_escape(value):
"""Escape a value for use as element text (not attributes)."""
if value is None:
return ""
return (_INVALID_XML.sub("", str(value))
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;"))
def _attr_escape(value):
"""Escape a value for use inside an attribute."""
if value is None:
return ""
return (_INVALID_XML.sub("", str(value))
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
.replace("'", "&apos;"))
def _rfc822(dt):
"""Format a datetime as an RFC 822 date, as <pubDate>/<date_time_gmt> expect."""
return dt.strftime("%a, %d %b %Y %H:%M:%S +0000")
def _post_url(site_url, slug):
return f"{site_url.rstrip('/')}/post/{slug}"
def _comment_dt(comment):
"""A comment's own timestamp.
Every comment used to carry the *post's* date, which made the exported feed
claim all comments were written when the post was published.
"""
try:
return datetime.strptime(comment["created_at"], "%Y-%m-%d %H:%M:%S")
except (KeyError, ValueError, TypeError):
return datetime.now(timezone.utc).replace(tzinfo=None)
def build_wxr(db, site_title, site_url, site_description):
"""Return the WXR document as a string.
`db` must be an open sqlite3 connection; `site_title`, `site_url` and
`site_description` describe the channel (the WordPress importer needs them).
"""
posts = db.execute(
"SELECT * FROM posts WHERE status = 'published' ORDER BY created_at DESC"
).fetchall()
# name -> slug, for turning WXR category names back into our category slugs.
cat_by_name = {slug: name for slug, name in
db.execute("SELECT slug, name FROM categories").fetchall()}
# Channel metadata comes first (WordPress's importer needs it before any
# <item>), so build everything into one list in document order.
out = []
out.append('<?xml version="1.0" encoding="UTF-8"?>')
out.append(
'<rss version="2.0"'
+ "".join(f' xmlns:{p}="{u}"' for p, u in NS)
+ '>'
)
out.append(" <channel>")
out.append(f" <title>{_xml_escape(site_title)}</title>")
out.append(f" <link>{_xml_escape(site_url.rstrip('/'))}</link>")
out.append(f" <description>{_xml_escape(site_description)}</description>")
out.append(' <language>en_US</language>')
out.append(' <docs>http://blogs.law.harvard.edu/tech/rss</docs>')
out.append(' <generator>Simple Blog WXR Export</generator>')
for p in posts:
url = _post_url(site_url, p["slug"])
created = datetime.strptime(p["created_at"], "%Y-%m-%d %H:%M:%S")
out.append(" <item>")
wxr_status = "publish" if p["status"] == "published" else "draft"
out.append(f' <wp:status>{_xml_escape(wxr_status)}</wp:status>')
out.append(f' <wp:post_name>{_xml_escape(p["slug"])}</wp:post_name>')
out.append(f" <title>{_xml_escape(p['title'])}</title>")
out.append(f" <link>{_xml_escape(url)}</link>")
out.append(f' <guid isPermaLink="true">{_xml_escape(url)}</guid>')
out.append(
f' <dc:creator>{_xml_escape(p["author"] or "editor")}</dc:creator>'
)
out.append(f" <pubDate>{_rfc822(created)}</pubDate>")
out.append(f" <dc:date>{_rfc822(created)}</dc:date>")
categories, tags = [], []
for cat in (p["category"] or "").split(","):
cat = cat.strip()
if not cat:
continue
slug_ = cat_by_name.get(cat, cat)
categories.append(slug_)
for tag in (p["tags"] or "").split(","):
tag = tag.strip()
if tag:
tags.append(tag)
for slug_ in categories:
out.append(
f' <category domain="category">{_xml_escape(slug_)}</category>'
)
for tag in tags:
out.append(
f' <category domain="post_tag">{_xml_escape(tag)}</category>'
)
# Comments attached to this post.
comments = db.execute(
"SELECT * FROM comments WHERE object_type = 'post' AND object_id = ? "
"ORDER BY created_at", (p["id"],)).fetchall()
for c in comments:
comment_link = url + f"#c{c['id']}"
attrs = [
f'ID="{c["id"]}"',
f'author="{_attr_escape(c["author"] or "")}"',
f'author_email="{_attr_escape(c["email"] or "")}"',
'author_url=""',
f'date_time_gmt="{_rfc822(_comment_dt(c))}"',
'comment_type=""',
'status="approved"',
f'permalink="{_attr_escape(comment_link)}"',
]
out.append(' <wfw:comment ' + ' '.join(attrs) + '>')
out.append(f" {_xml_escape(c['body'])}")
out.append(" </wfw:comment>")
out.append(f' <wfw:commentRss>{_xml_escape(url + "#comments")}</wfw:commentRss>')
out.append(f" <slash:comments>{len(comments)}</slash:comments>")
out.append(f" <content:encoded>{_xml_escape(p['body'])}</content:encoded>")
out.append(" </item>")
out.append(" </channel>")
out.append("</rss>")
return "\n".join(out)