-
Notifications
You must be signed in to change notification settings - Fork 3
/
webpages.py
218 lines (177 loc) · 6.37 KB
/
webpages.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
# encoding: utf-8
import os.path
from functools import wraps
from pytz import timezone
import csv
import tempfile
import flask
import auth
import database
office_defs = {
'deputy': u"deputat",
'senator': u"senator",
}
webpages = flask.Blueprint('webpages', __name__)
def with_template(template_name):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if result is None:
result = {}
if isinstance(result, (dict,)):
return flask.render_template(template_name, **result)
else:
return result
return wrapper
return decorator
@webpages.route('/test_error')
@auth.require_admin
def test_error():
raise ValueError("Just checking.")
@webpages.route('/stats')
@auth.require_admin
@with_template('stats.html')
def stats():
from datetime import datetime, time
ContentVersion = database.ContentVersion
today_0 = datetime.combine(datetime.utcnow(), time())
edits_today = ContentVersion.query.filter(ContentVersion.time > today_0)
return {
'data': {
'edits_today': edits_today.count(),
'users': database.User.query.count(),
'persons': database.Person.query.count(),
},
}
@webpages.route('/download')
def download():
fmt = flask.request.args.get('format')
def get_meta(person):
meta = {}
for key in database.meta_defs:
value = person.get_meta(key)
if value:
meta[key] = value
return meta
utf8 = lambda v: unicode(v).encode('utf-8')
fields = ['id', 'name'] + sorted(database.prop_defs.keys())
header = dict((k, utf8(v)) for k, v in database.prop_defs.iteritems())
header.update(id='id', name='Nume')
csvfile = tempfile.NamedTemporaryFile()
csvwriter = csv.DictWriter(csvfile, fields)
csvwriter.writerow(header)
for person_id in database.db.session.query(database.Person.id):
person = database.Person.query.get(person_id)
bytes_row = {'id': str(person.id), 'name': utf8(person.name)}
for key, value_list in person.get_content().iteritems():
bytes_row[key] = '; '.join(utf8(v) for v in value_list)
csvwriter.writerow(bytes_row)
csvfile.seek(0)
return flask.send_file(csvfile, mimetype='text/csv')
@webpages.route('/person/<int:person_id>')
@with_template('person.html')
def person(person_id):
person = database.Person.query.get_or_404(person_id)
return {
'person': person,
'person_content': person.get_content(),
}
@webpages.route('/person/<int:person_id>/edit', methods=['GET', 'POST'])
@auth.require_login
@with_template('edit.html')
def edit(person_id):
person = database.Person.query.get_or_404(person_id)
content = person.get_content()
user = flask.g.user
if flask.request.method == 'POST':
form = flask.request.form
new_content = {}
for field_name in database.prop_defs:
values = [v.strip() for v in form.getlist(field_name) if v.strip()]
if values:
new_content[field_name] = values
if new_content != content:
person.save_content_version(new_content, user)
database.db.session.commit()
flask.flash(u"Conținutul a fost salvat", 'success')
else:
flask.flash(u"Conținutul este neschimbat")
url = flask.url_for('webpages.person', person_id=person.id)
return flask.redirect(url)
person = database.Person.query.get_or_404(person_id)
return {
'person': person,
'person_content': person.get_content(),
}
@webpages.route('/by_hpol_id/<int:hpol_id>')
def hpol_view(hpol_id):
query = database.PersonMeta.query.filter_by(key='hpol_id', value=hpol_id)
person = query.first_or_404().person
return flask.redirect(flask.url_for('.person', person_id=person.id))
@webpages.route('/by_hpol_id/<int:hpol_id>/edit')
def hpol_edit(hpol_id):
query = database.PersonMeta.query.filter_by(key='hpol_id', value=hpol_id)
person = query.first_or_404().person
return flask.redirect(flask.url_for('.edit', person_id=person.id))
@webpages.route('/history')
@with_template('all_history.html')
def all_history():
time_desc = database.ContentVersion.time.desc()
return {
'versions': iter(database.ContentVersion.query.order_by(time_desc)),
}
@webpages.route('/person/<int:person_id>/history')
@with_template('history.html')
def history(person_id):
person = database.Person.query.get_or_404(person_id)
time_desc = database.ContentVersion.time.desc()
person_versions = person.versions
person_versions.sort(key=lambda v: v.time, reverse=True)
return {
'person': person,
'versions': person_versions,
}
@webpages.route('/person/<int:person_id>/diff/<int:a_id>...<int:b_id>')
@with_template('diff.html')
def diff(person_id, a_id, b_id):
person = database.Person.query.get_or_404(person_id)
person_versions = (database.ContentVersion.query
.filter_by(person_id=person.id))
a = person_versions.filter_by(id=a_id).first_or_404()
b = person_versions.filter_by(id=b_id).first_or_404()
def flat_version_items(version):
items = []
for key, values in version.get_content().items():
for value in values:
items.append((key, value))
return items
return {
'person': person,
'version_a': a,
'version_b': b,
'version_a_items': flat_version_items(a),
'version_b_items': flat_version_items(b),
}
@webpages.route('/')
@with_template('search.html')
def search():
q = flask.request.args.get('q')
if q is None:
return {}
persons = database.Person.objects_current()
for part in q.split():
persons = persons.filter(database.Person.name.like('%' + part + '%'))
return {
'q': q,
'count': persons.count(),
'persons': persons[:50],
}
def init_app(app):
app.register_blueprint(webpages)
app.jinja_env.globals['known_names'] = database.prop_defs
app.jinja_env.globals['office_label'] = office_defs
local_timezone = timezone(app.config['TIMEZONE'])
def filter_datetime(utc_value, fmt='%d %b, %H:%M'):
return local_timezone.fromutc(utc_value).strftime(fmt)
app.jinja_env.filters['datetime'] = filter_datetime