blog/flaskr/generate_rss.py

69 lines
2.4 KiB
Python

from datetime import datetime
import sqlite3
from bs4 import BeautifulSoup
from markdown import markdown
def soup_append_multiple_tags(soup: BeautifulSoup, children: dict) -> None:
for name, string in children.items():
soup.append(soup.new_tag(name))
soup.find_all(name)[-1].string = string
def post_find_first_plain_line(post: str) -> str:
while post:
if post[0].isalnum():
break
end = post.find("\n")
post = post[end+1:]
end = post.find("\n")
return post[:end]
def generate_feed(db):
soup = BeautifulSoup(features="xml")
soup.append(soup.new_tag("rss", version="2.0"))
rss = soup.rss
rss["xmlns:atom"] = "http://www.w3.org/2005/Atom"
rss["xmlns:content"] = "http://purl.org/rss/1.0/modules/content/"
rss.append(soup.new_tag("channel"))
channel = rss.channel
channel_children = {
"description": "Blog posts from allsparkinfinite's blog",
"link": "https://blog.allsparkinfinite.name",
"title": "blogsparkinfinite",
"docs": "https://rssboard.org/rss-specification",
"language": "en-IN",
"lastBuildDate": datetime.now().strftime("%a, %d %b %Y %T +0530"),
"ttl": "240",
}
soup_append_multiple_tags(channel, channel_children)
channel.append(channel.new_tag("atom:link"))
channel.find_all("atom:link")[-1]["href"] = "https://blog.allsparkinfinite.name/rss/"
channel.find_all("atom:link")[-1]["rel"] = "self"
channel.find_all("atom:link")[-1]["type"] = "application/rss+xml"
channel.append(channel.new_tag("atom:link"))
channel.find_all("atom:link")[-1]["href"] = "https://blog.allsparkinfinite.name/"
channel.find_all("atom:link")[-1]["rel"] = "alternate"
channel.find_all("atom:link")[-1]["type"] = "text/html"
posts = db.execute("SELECT * FROM post").fetchall()
posts.reverse()
for post in posts:
channel.append(soup.new_tag("item"))
item = channel.find_all("item")[-1]
item_children = {
"description": post_find_first_plain_line(post[4]),
"guid": f"https://blog.allsparkinfinite.name/{post[0]}/",
"pubDate": post[2].strftime("%a, %d %b %Y %T GMT"),
"title": post[3],
"content:encoded": markdown(post[4]),
}
soup_append_multiple_tags(item, item_children)
with open("flaskr/static/rss.xml", "w") as f:
f.write(soup.prettify())