-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
319 lines (217 loc) · 8.28 KB
/
server.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
from jinja2 import StrictUndefined
from flask import Flask, render_template, request, flash, redirect, session, abort, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from model import connect_to_db, db,Character, Relationship, Series, User, CharacterSeries, CharacterRating, SeriesRating
import json
import bcrypt
app = Flask(__name__)
app.secret_key = "TARDIS"
app.jinja_env.undefined = StrictUndefined
@app.route('/')
def display_index():
"""Display index template."""
characters = Character.all()
series = Series.all()
return render_template("index.html",
characters=characters,
series=series)
# GET method
@app.route('/character/<character_name>')
def display_character(character_name):
"""Display character info template."""
# Using CLASS METHODS instead (to-do):
# character_id = request.args.get("character")
# character = Character.by_id(character_id)
# Want all querying done in model file(s) only if possible!
character = Character.query.filter_by(name=character_name).first()
user_id = session.get("user_id")
if user_id:
user_rating = CharacterRating.query.filter_by(
char_id=character.char_id, user_id=user_id).first()
else:
user_rating = None
rating_scores = [r.score for r in character.character_ratings]
if rating_scores:
avg_rating = float(sum(rating_scores)) / len(rating_scores)
avg_rating = 'Average rating for this character: %.1f' % avg_rating
# Work out how to display int only if avg isn't a float,
# float if it is, and to only 1 decimal point
else:
avg_rating = "Not yet rated."
if character:
f = open(character.bio, 'r')
char_bio = f.read()
char_bio = char_bio.decode('utf-8')
relationships = character.relationships()
appearances = character.appearances
return render_template("character.html",
character=character,
char_bio=char_bio,
relationships=relationships,
appearances=appearances,
user_rating=user_rating,
avg_rating=avg_rating)
else:
abort(404)
@app.route('/character/<character_name>', methods=['POST'])
def post_character_rating(character_name):
# Get form variables
score = int(request.form["score"])
user_id = session.get("user_id")
if not user_id:
raise Exception("No user logged in.")
character = Character.query.filter_by(name=character_name).first()
rating = CharacterRating.query.filter_by(user_id=user_id, char_id=character.char_id).first()
# Come back and re-factor this once the ratings system for both
# characters & series are in place
if rating:
rating.score = score
# flash("Already rated.")
else:
rating = CharacterRating(user_id=user_id, char_id=character.char_id, score=score)
flash("Rating added.")
db.session.add(rating)
db.session.commit()
return redirect("/character/%s" % (character.name))
# GET method
@app.route('/series/<series_name>')
def display_series(series_name):
"""Display series info template."""
series = Series.query.filter_by(name=series_name).first()
user_id = session.get("user_id")
if user_id:
user_rating = SeriesRating.query.filter_by(
series_id=series.series_id, user_id=user_id).first()
else:
user_rating = None
rating_scores = [r.score for r in series.series_ratings]
if rating_scores:
avg_rating = float(sum(rating_scores)) / len(rating_scores)
avg_rating = 'Average rating for this series: %.1f' % avg_rating
# Work out how to display int only if avg isn't a float, float if it is?
else:
avg_rating = "Not yet rated."
if series:
f = open(series.synopsis, 'r')
synopsis = f.read()
synopsis = synopsis.decode('utf-8')
characters = series.characters
return render_template("series.html",
series=series,
synopsis=synopsis,
characters=characters,
user_rating=user_rating,
avg_rating=avg_rating)
else:
abort(404)
@app.route('/series/<series_name>', methods=['POST'])
def post_series_rating(series_name):
score = int(request.form["score"])
user_id = session.get("user_id")
if not user_id:
raise Exception("No user logged in.")
series = Series.query.filter_by(name=series_name).first()
rating = SeriesRating.query.filter_by(user_id=user_id, series_id=series.series_id).first()
# Come back and re-factor this once the ratings system for both
# characters & series are in place
if rating:
rating.score = score
# flash("Already rated.")
else:
rating = SeriesRating(user_id=user_id, series_id=series.series_id, score=score)
flash("Rating added.")
db.session.add(rating)
db.session.commit()
return redirect("/series/%s" % (series.name))
@app.route('/login', methods=['GET'])
def login_form():
"""Show login form."""
return render_template("login_form.html")
@app.route('/login', methods=['POST'])
def login_process():
"""Process login."""
# Get form variables
email = request.form["email"]
password = request.form["password"]
password = password.encode('utf8')
hashedpass = password.encode('utf8')
user = User.query.filter_by(email=email).first()
hashedpass = user.password.encode('utf8')
if not user:
flash("No user with that email found, please register.")
return redirect("/login")
if bcrypt.checkpw(password, hashedpass):
session["user_id"] = user.user_id
flash("Welcome to the Whoniverse.")
return redirect("/")
else:
flash("Incorrect password, try again.")
return redirect("/login")
@app.route('/logout')
def logout():
"""Log out."""
del session["user_id"]
flash("Logged Out.")
return redirect("/")
@app.route('/register', methods=['GET'])
def register_form():
"""Show form for user signup."""
return render_template("register_form.html")
@app.route('/register', methods=['POST'])
def register_process():
"""Process registration."""
# Get form variables
email = request.form["email"]
password = request.form.get("password")
password = password.encode('utf8')
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
new_user = User(email=email, password=hashed)
db.session.add(new_user)
db.session.commit()
flash("User %s added." % email)
return redirect("/users/%s" % new_user.user_id)
@app.route("/users")
def user_list():
"""Show list of users."""
users = User.query.all()
return render_template("user_list.html", users=users)
@app.route("/users/<int:user_id>")
def display_user_info(user_id):
"""Show info about single user by id."""
user = User.query.get(user_id)
return render_template("user.html", user=user)
@app.route("/characters.json")
def get_data_for_d3():
json = {"nodes":[], "links":[]}
characters = Character.all()
relationships = Relationship.query.all()
characters = sorted(characters, key=lambda c:c.char_id)
for c in characters:
node = {}
node["name"] = c.name
node["group"] = c.group
json["nodes"].append(node)
for r in relationships:
link = {}
link["source"] = r.char1_id - 1
link["target"] = r.char2_id - 1
link["value"] = r.threshold
json["links"].append(link)
return jsonify(json)
# Render template for connections.html
@app.route('/visualize')
def show_d3():
return render_template("connections.html")
@app.route('/landing')
def render_landing_page():
return render_template("landing.html")
if __name__ == "__main__":
# Have to set debug=True here, since it has to be True at the point that
# the DebugToolbarExtension is invoked
# Do not debug for demo
app.debug = True
app.jinja_env.auto_reload = True
connect_to_db(app)
# Use the DebugToolbar
# DebugToolbarExtension(app)
app.run(host="0.0.0.0")