-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblog.py
More file actions
83 lines (65 loc) · 2.22 KB
/
Copy pathblog.py
File metadata and controls
83 lines (65 loc) · 2.22 KB
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
import sqlite3
import json
from neptune.server import NServer
from neptune.response import JSONResponse, HTTPResponse, HTMLResponse
def init_db():
try:
cursor.execute("""
CREATE TABLE blog (id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT);
""")
db_connection.commit()
except:
pass
def get_all_posts():
post_data = db_connection.execute("""SELECT id, title, content FROM blog;""")
posts = []
for post in post_data:
posts.append({
'id': post[0],
'title': post[1],
'content': post[2],
'url': '/post?id={}'.format(post[0])
})
return posts
def new_post(title, content):
cursor.execute("""
INSERT INTO blog (title, content) VALUES (?, ?)
""", (title, content))
db_connection.commit()
def get_post(pid):
post_data = db_connection.execute("""SELECT id, title, content FROM blog WHERE id = {}""".format(pid))
post_data = [i for i in post_data][0]
return {'id': post_data[0], 'title': post_data[1], 'content': post_data[2]}
class Home(object):
def get(self):
return HTMLResponse("home.html", {'posts': get_all_posts()})
class Archive(object):
def get(self):
return HTMLResponse("archive.html", {'posts': get_all_posts()})
class NewPost(object):
def post(self):
data = self.request.request_data
data = json.loads(data)
new_post(data['title'], data['content'])
return JSONResponse({"status": "OK",
"message": "New Post Successfully Added"})
class NewPostPage(object):
def get(self):
return HTMLResponse("new.html")
class GetPost(object):
def get(self):
pid = self.request.params['id']
return HTMLResponse("blog.html", {'post': get_post(pid)})
app = NServer(port=5000)
app.router.add_rule('/', Home)
app.router.add_rule('/archive', Archive)
app.router.add_rule('/new', NewPost)
app.router.add_rule('/newpost', NewPostPage)
app.router.add_rule('/post', GetPost)
if __name__ == "__main__":
db_connection = sqlite3.connect(".blog.db")
cursor = db_connection.cursor()
init_db()
app.run()