-
Notifications
You must be signed in to change notification settings - Fork 0
/
readlist.py
230 lines (173 loc) · 6.26 KB
/
readlist.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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from flask import Flask, g, request, flash, url_for, redirect, jsonify, escape
from flask import render_template
from jinja2 import filters
from jinja2.utils import urlize
from contextlib import closing
import sqlite3
import os
import datetime
#CONFIG
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
SCHEMA_PATH = os.path.join(PROJECT_PATH, 'schema.sql')
DATABASE = os.path.join(PROJECT_PATH, 'readlist.db')
SECRET_KEY = 'iloveponies'
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
book_html = """
<li>
<span class="%s"></span>
<div class="content" id="%s">
<nav id="book_nav">
<a href="#" class="edit">edit |</a>
<a href="#" class="finish">finish | </a>
<a href="#" class="remove">remove</a>
</nav>
<h3>%s</h3>
<p class="desc">%s</p>
<time>added: <strong>%s</strong></time>
</div>
<div class="edit" id="%s" style="display:none">
<h3>edit book</h3>
<p>
<strong>Title</strong>
<input class="edit_title" type="text" name="edit_title" value="%s">
</p>
<p>
<strong>Description</strong>
<textarea rows="10" cols="50" class="edit_desc" name="edit_desc">%s</textarea>
</p>
<button type="submit" name="edit_submit">save</button>
</div>
</li>
""".strip()
date_format = "%b %d, %Y @ %H:%m"
def datetimeformat(value, format=date_format):
return value.strftime(format)
filters.FILTERS['datetimeformat'] = datetimeformat
def convert_date(s):
date = s.split('.')[0]
return datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
def init_db():
print app.config
with closing(connect_db()) as db:
with app.open_resource(app.config['SCHEMA_PATH']) as f:
db.cursor().executescript(f.read())
db.commit()
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
@app.before_request
def before_requrest():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
g.db.close()
@app.route('/')
def index():
cur = g.db.execute('select * from books order by id desc')
books = []
for row in cur.fetchall():
d = {}
d['id'] = row[0]
d['title'] = row[1]
d['description'] = row[2]
d['finished'] = row[3]
d['created'] = convert_date(row[4])
books.append(d)
return render_template('index.html', books=books)
@app.route('/add', methods=['POST'])
def add_book():
title = escape(request.form.get('title', ''))
description = escape(request.form.get('description', ''))
created = datetime.datetime.now()
if title and description:
error = None
#some basic dupe checking
existing = g.db.execute('select * from books where title like (?)', [title]).fetchall()
g.db.commit()
if existing:
error = u"A book with this title already exists! DUN DUN DUN ..."
if request.is_xhr:
if error:
return jsonify(error=error)
#create new book
g.db.execute('insert into books (title, description, created) values (?, ?, ?)', [title, description, created])
g.db.commit()
book_id = g.db.execute('select id from books where title like (?)', [title]).fetchone()[0]
html = book_html % (
'reading', #assume book is not finished if just added
book_id,
title,
urlize(description),
datetimeformat(created),
book_id,
title,
description,
)
return jsonify(html=html)
else:
return u"XHR requests only."
else:
return jsonify(error="Missing the stuffs!")
@app.route('/update', methods=['POST'])
def update_book():
book_id = escape(request.form.get('book_id', ''))
edit_title = escape(request.form.get('edit_title', ''))
edit_desc = escape(request.form.get('edit_desc', ''))
if book_id and edit_title and edit_desc:
if request.is_xhr:
#update the book informations and return html
g.db.execute('update books SET title = ?, description = ? WHERE rowid = ?', (edit_title, edit_desc, int(book_id)))
g.db.commit()
book = g.db.execute('select * from books where id = ?', [int(book_id)]).fetchone()
g.db.commit()
html = book_html % (
'finished' if book[3] else 'reading', #book could be finished
book[0], #id
book[1], #title
urlize(book[2]), #desc
datetimeformat(convert_date(book[4])),
book[0],
book[1],
book[2],
)
return jsonify(success=True, html=html)
else:
return u"XHR requests only."
else:
return jsonify(error=u"Missing all the stuffs.")
@app.route('/remove', methods=['POST'])
def remove_book():
book_id = escape(request.form.get('book_id', None))
if book_id:
if request.is_xhr:
#delete book for id
g.db.execute('delete from books where id is (?)' , [book_id])
g.db.commit()
return jsonify(msg=u"D: book was removed!")
else:
return u"XHR requests only."
else:
return jsonify(error="No book id? o.o")
@app.route('/finish', methods=['POST'])
def finish_book():
book_id = escape(request.form.get('book_id', None))
if book_id:
if request.is_xhr:
#update book, set finished to 1
g.db.execute('update books SET finished = ? WHERE rowid = ?', [1, book_id])
g.db.commit()
return jsonify(msg=u"Woot! You finished ze book! Hug yourself. Do it.")
else:
return u"XHR requests only."
else:
return jsonify(error=u"No book id? o.o")
@app.route('/sort', methods=['GET'])
def sort():
#sort by: all | finished
pass
@app.errorhandler(404)
def page_not_found(error):
return render_template('not_found.html'), 404
if __name__ == '__main__':
app.run()