diff options
Diffstat (limited to 'rss.py')
-rw-r--r-- | rss.py | 64 |
1 files changed, 64 insertions, 0 deletions
@@ -0,0 +1,64 @@ | |||
1 | import os | ||
2 | import jinja2 | ||
3 | |||
4 | import glob | ||
5 | from bs4 import BeautifulSoup | ||
6 | |||
7 | |||
8 | class FilePathLoader(jinja2.BaseLoader): | ||
9 | def __init__(self, cwd): | ||
10 | self.cwd = cwd | ||
11 | |||
12 | def get_source(self, environment, template): | ||
13 | filename = os.path.join(self.cwd, template) | ||
14 | |||
15 | try: | ||
16 | with open(filename, 'r') as f: | ||
17 | contents = f.read() | ||
18 | except IOError: | ||
19 | raise jinja2.TemplateNotFound(filename) | ||
20 | |||
21 | return contents, filename, lambda: False | ||
22 | |||
23 | |||
24 | def render_template(cwd, template_path, context): | ||
25 | env = jinja2.Environment(loader=FilePathLoader(cwd)) | ||
26 | return env.get_template(template_path).render(context) | ||
27 | |||
28 | |||
29 | def main(): | ||
30 | |||
31 | filenames = glob.glob("./_build/html/_posts/*/*/*.html") | ||
32 | print(filenames) | ||
33 | |||
34 | posts = [] | ||
35 | |||
36 | for p in filenames: | ||
37 | soup = BeautifulSoup(open(p), "html5lib") | ||
38 | body = soup.find_all("div", class_="body")[0].text | ||
39 | |||
40 | posts.append({ | ||
41 | "title": soup.title.string, | ||
42 | "body": body, | ||
43 | "date_rss": body[body.find("Publish Date:")+13:body.find("Publish Date:")+23], | ||
44 | "permalink": "/".join(p.split("/")[3:]) | ||
45 | }) | ||
46 | |||
47 | context = { | ||
48 | "site": { | ||
49 | "name": "Hello World", | ||
50 | "url": "https://blog.jinwei.me", | ||
51 | "tagline": "Freedom is my birth right and I shall have it." | ||
52 | }, | ||
53 | "posts": posts | ||
54 | } | ||
55 | |||
56 | return render_template( | ||
57 | ".", | ||
58 | "all.rss.xml", | ||
59 | context | ||
60 | ) | ||
61 | |||
62 | |||
63 | if __name__ == '__main__': | ||
64 | print(main()) | ||