-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
108 lines (76 loc) · 2.41 KB
/
app.py
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
from os import mkdir
from os.path import isdir, abspath
from sqlite3 import connect as sqlite_connect
from sqlite3 import Row as sqlite_row
from json import dumps as json_dumps
from bottle import get, post, delete, route, run, static_file, HTTPResponse, response, request
STATIC_ROOT = abspath("bower_components")
HOME = open("home.html", "r").read()
SCHEMA = """
create table Diagram (
name text primary key,
content text not null
);
"""
def db_integrity_check(conn):
c = conn.cursor()
c.execute("select sql from sqlite_master where type='table' "
"and name in ('Diagram')")
return len(c.fetchall()) == 1
conn = sqlite_connect("diagrams.db", check_same_thread=False)
conn.row_factory = sqlite_row
if not db_integrity_check(conn):
print("Integrity check failed... Recreating database.")
conn.cursor().executescript(SCHEMA)
conn.commit()
@get("/diagrams")
def get_diagrams():
diagrams = {}
response.content_type = "application/json"
c = conn.cursor()
c.execute("select name, content from Diagram")
for row in c.fetchall():
diagrams[row["name"]] = row["content"]
return json_dumps(diagrams)
@delete("/diagram/<name>")
def delete_diagram(name):
successful = True
c = conn.cursor()
c.execute("select name from Diagram where name = ?", (name, ))
if not len(c.fetchall()) == 0:
c.execute("delete from Diagram where name = ?", (name, ))
print("Delete successful: '%s'" % name)
else:
print("Delete unsuccessful: '%s' not found" % name)
successful = False
conn.commit()
return HTTPResponse(status=200 if successful else 404)
@post("/diagram/<name>")
def post_diagram(name):
content = request.forms.get("content")
c = conn.cursor()
c.execute("select name from Diagram where name = ?", (name, ))
if len(c.fetchall()) == 0:
c.execute("insert into Diagram values (?, ?)", (name, content))
print("Saved new diagram: '%s'" % name)
else:
c.execute("update Diagram set content = ? where name = ?",
(content, name))
print("Diagram override: '%s'" % name)
conn.commit()
@get("/diagram/<name>")
def get_diagram(name):
c = conn.cursor()
c.execute("select content from Diagram where name = ?", (name))
result = c.fetchall()
if len(result) == 0:
return HTTPResponse(status=404)
else:
return result[0]
@get("/static/<filepath:path>")
def server_static(filepath):
return static_file(filepath, root=STATIC_ROOT)
@get("/")
def home():
return HOME
run(host="localhost", port=8080, debug=True)