1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
import on_this_day
import sys
import sqlite3
from datetime import datetime
from config import config
from http.server import HTTPServer, BaseHTTPRequestHandler
def format_datetime(date):
return str(date)
def generate_item(item):
return f"""<item>
<title><![CDATA[{item["title"]}]]></title>
<description><![CDATA[{item["description"]}]]></description>
<link>{config["host"]}/{item["guid"]}</link>
<guid isPermaLink="true">{item["guid"]}</guid>
<pubDate>{item["createdAt"]}</pubDate>
</item>"""
def generate_feed(items):
return f"""<rss version="2.0"><channel>
<title>On This Day</title>
<description>Daily posts of stuff for today</description>
<lastBuildDate>{format_datetime(datetime.now())}</lastBuildDate>
{"".join(generate_item(item) for item in items)}
</channel></rss>"""
def generate_ul(items):
return f"""<ul>
{f"<li>{'</li><li>'.join(items)}</li>"}
<ul>"""
def get_description():
list_items = [
(on_this_day.get_old_news, "old news"),
(on_this_day.get_peanuts, "peanuts"),
(on_this_day.get_calvin_and_hobbes, "calvin and hobbes"),
(on_this_day.get_today_wikipedia, "wikipedia"),
(on_this_day.get_week_holidays, "holiday"),
(on_this_day.get_crossword, "crossword"),
(on_this_day.year_progress_bar, "year progress"),
(on_this_day.get_homepage_links, "homepage links"),
]
items = []
for func, name in list_items:
try:
items.append(func())
except Exception as e:
items.append(f"Error getting {name}")
print("Exception:", e)
ul = generate_ul(items)
div_items = [
(on_this_day.get_today_wikiquote, "wikiquote"),
(on_this_day.get_thoreau, "thoreau"),
]
items = []
for func, name in div_items:
try:
items.append(func())
except:
items.append(f"Error getting {name}")
divs = f"<div>{'</div><div>'.join(items)}</div>"
return f"""
<h1>On this day</h1>
{ul}
{divs}
"""
def setup(con):
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS items (guid, title, description, createdAt)")
con.commit()
cur.close()
def insert_today():
con = sqlite3.connect(config["db"])
now = datetime.now()
cur = con.cursor()
cur.execute(
"INSERT INTO items values (?, ?, ?, ?)",
(now.isoformat(), str(now), get_description(), format_datetime(now))
)
con.commit()
cur.close()
def get_all(con):
cur = con.cursor()
items = []
for (guid, title, description, createdAt) in cur.execute("SELECT guid, title, description, createdAt FROM items"):
items.append({
"guid": guid,
"title": title,
"description": description,
"createdAt": createdAt,
})
cur.close()
return generate_feed(items)
def get_one_desc(con, guid):
cur = con.cursor()
description = next(
cur.execute("SELECT description FROM items WHERE guid=:guid", {"guid": guid}))[0]
cur.close()
print(description)
return description
class RssHTTPRequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args):
BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(get_all(con), "utf-8"))
else:
guid = self.path[1:]
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(get_one_desc(con, guid), "utf-8"))
con = None
def server():
print("Starting http server")
http = HTTPServer(("", 8000), RssHTTPRequestHandler)
print("serving forever")
http.serve_forever()
def test():
print(get_description())
if __name__ == "__main__":
if len(sys.argv) == 1:
con = sqlite3.connect(config["db"])
setup(con)
server()
elif sys.argv[1] == "insert":
insert_today()
elif sys.argv[1] == "test":
test()
|