-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
426 lines (288 loc) · 10.9 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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import os
from flask import Flask, render_template, request, flash, redirect, session, g, abort, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from sqlalchemy.exc import IntegrityError
from itertools import chain
from forms import UserAddForm, LoginForm, MessageForm, EditUserForm, CommentForm
from models import db, connect_db, User, Message, Like, Comment
CURR_USER_KEY = "curr_user"
app = Flask(__name__)
# Get DB_URI from environ variable (useful for production/testing) or,
# if not set there, use development local db.
app.config['SQLALCHEMY_DATABASE_URI'] = (
os.environ.get('DATABASE_URL', 'postgres:///warbler'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = False
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', "default_secret_key")
toolbar = DebugToolbarExtension(app)
connect_db(app)
##############################################################################
# User signup/login/logout
@app.before_request
def add_user_to_g():
"""If we're logged in, add curr user to Flask global."""
if CURR_USER_KEY in session:
g.user = User.query.get(session[CURR_USER_KEY])
else:
g.user = None
def do_login(user):
"""Log in user."""
session[CURR_USER_KEY] = user.id
def do_logout():
"""Logout user."""
if CURR_USER_KEY in session:
del session[CURR_USER_KEY]
@app.route('/signup', methods=["GET", "POST"])
def signup():
"""Handle user signup.
Create new user and add to DB. Redirect to home page.
If form not valid, present form.
If the there already is a user with that username: flash message
and re-present form.
"""
form = UserAddForm()
if form.validate_on_submit():
try:
user = User.signup(
username=form.username.data,
password=form.password.data,
email=form.email.data,
image_url=form.image_url.data or User.image_url.default.arg,
)
db.session.commit()
except IntegrityError as e:
flash("Username already taken", 'danger')
return render_template('users/signup.html', form=form)
do_login(user)
return redirect("/")
else:
return render_template('users/signup.html', form=form)
@app.route('/login', methods=["GET", "POST"])
def login():
"""Handle user login."""
form = LoginForm()
if form.validate_on_submit():
user = User.authenticate(form.username.data,
form.password.data)
if user:
do_login(user)
flash(f"Hello, {user.username}!", "success")
return redirect("/")
flash("Invalid credentials.", 'danger')
# if... request.isGUest or something, then authenticate as guest
return render_template('users/login.html', form=form)
@app.route('/logout')
def logout():
"""Handle logout of user."""
do_logout()
flash("you have been successfully logged out!", "success")
return redirect('/')
##############################################################################
# Like routes
@app.route('/like', methods=["POST"])
def add_like():
msg_id = request.json.get('msg-id')
is_existing = Like.query.filter_by(message_id=msg_id, user_id=g.user.id).first()
msg = Message.query.filter_by(id=msg_id).first_or_404()
if is_existing is None:
like = Like(user_id=g.user.id, message_id=msg_id)
db.session.add(like)
db.session.commit()
else:
db.session.delete(is_existing)
db.session.commit()
resp = {
"likes": len(msg.likes),
"is-liked": msg.is_liked_by(g.user.id),
"msgId": msg.id,
"userImg": g.user.image_url
}
return jsonify(resp)
@app.route('/likes')
def render_likes_page():
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
liked_msg_id = [l.message_id for l in g.user.likes]
messages = Message.query.filter(Message.id.in_(liked_msg_id)).order_by(Message.timestamp.desc()).all()
return render_template('/users/likes.html', messages=messages, user=g.user)
##############################################################################
# General user routes:
@app.route('/users')
def list_users():
"""Page with listing of users.
Can take a 'q' param in querystring to search by that username.
"""
search = request.args.get('q')
if not search:
users = User.query.all()
else:
users = User.query.filter(User.username.like(f"%{search}%")).all()
return render_template('users/index.html', users=users)
@app.route('/users/<int:user_id>')
def users_show(user_id):
"""Show user profile."""
user = User.query.get_or_404(user_id)
# snagging messages in order from the database;
# user.messages won't be in order by default
messages = (Message
.query
.filter(Message.user_id == user_id)
.order_by(Message.timestamp.desc())
.limit(100)
.all())
return render_template('users/show.html', user=user, messages=messages)
@app.route('/users/<int:user_id>/following')
def show_following(user_id):
"""Show list of people this user is following."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
user = User.query.get_or_404(user_id)
return render_template('users/following.html', user=user)
@app.route('/users/<int:user_id>/followers')
def users_followers(user_id):
"""Show list of followers of this user."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
user = User.query.get_or_404(user_id)
return render_template('users/followers.html', user=user)
@app.route('/users/follow/<int:follow_id>', methods=['POST'])
def add_follow(follow_id):
"""Add a follow for the currently-logged-in user."""
followee = User.query.get(follow_id)
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
if g.user.is_following(followee):
g.user.following.remove(followee)
else:
g.user.following.append(followee)
db.session.commit()
load = {
"followeeId": followee.id,
"isFollowing": g.user.is_following(followee)
}
return jsonify(load)
@app.route('/users/profile', methods=["GET", "POST"])
def profile():
"""Update profile for current user."""
## if user not logged in, redirect
if not g.user:
flash("You must be logged in to view this page","danger")
return redirect('/')
form = EditUserForm(obj=g.user)
if form.validate_on_submit():
pw = form.password.data
user = User.authenticate(g.user.username, pw) # returns user or false
if user:
for k, v in form.data.items():
if k != 'csrf_token' and k != 'password':
setattr(user, k, v)
db.session.commit()
return redirect(f'/users/{g.user.id}')
else:
form.password.errors = ["invalid password"]
return render_template('/users/edit.html', form=form)
@app.route('/users/delete', methods=["POST"])
def delete_user():
"""Delete user."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
do_logout()
db.session.delete(g.user)
db.session.commit()
return redirect("/signup")
##############################################################################
# Comment routes:
@app.route('/messages/comments', methods=["POST"])
def add_comment():
""" add comment to message """
try:
msg_id = request.json.get('msgId')
text = request.json.get('text')
comment = Comment(text=text, message_id=msg_id, user_id=g.user.id)
db.session.add(comment)
db.session.commit()
return jsonify(comment.serialize())
except IntegrityError as e:
return e
##############################################################################
# Messages routes:
@app.route('/messages/new', methods=["GET", "POST"])
def messages_add():
"""Add a message:
Show form if GET. If valid, update message and redirect to user page.
"""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
form = MessageForm()
if form.validate_on_submit():
msg = Message(text=form.text.data)
g.user.messages.append(msg)
db.session.commit()
return redirect(f"/users/{g.user.id}")
return render_template('messages/new.html', form=form)
@app.route('/messages/<int:message_id>', methods=["GET", "POST"])
def messages_show(message_id):
"""Show a message."""
if g.user:
if request.method == "POST":
msg = Message.query.get(message_id)
serialized_msg = msg.serialize()
serialized_msg['comments'] = [c.serialize() for c in msg.comments]
return jsonify(serialized_msg)
msg = Message.query.get_or_404(message_id)
return render_template('messages/show.html', message=msg)
else:
flash ('You must be logged in to view this content', 'danger')
return render_template('home-anon.html')
@app.route('/messages/<int:message_id>/delete', methods=["POST"])
def messages_destroy(message_id):
"""Delete a message."""
msg = Message.query.get(message_id)
if msg.user_id != g.user.id:
flash("Access unauthorized.", "danger")
return redirect('/401'), 401
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
db.session.delete(msg)
db.session.commit()
return jsonify(message_id)
##############################################################################
# Homepage and error pages
@app.route('/')
def homepage():
"""Show homepage:
- anon users: no messages
- logged in: 100 most recent messages of followees
"""
if g.user:
following_users_id = [u.id for u in g.user.following]
following_users_id.append(g.user.id)
messages = Message.query.filter(Message.user_id.in_(following_users_id)).order_by(Message.timestamp.desc()).all()
return render_template('home.html', messages=messages)
else:
return render_template('home-anon.html')
@app.errorhandler(401)
def show_401(error):
return 'oof', 401
##############################################################################
# Turn off all caching in Flask
# (useful for dev; in production, this kind of stuff is typically
# handled elsewhere)
#
# https://stackoverflow.com/questions/34066804/disabling-caching-in-flask
@app.after_request
def add_header(req):
"""Add non-caching headers on every request."""
req.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
req.headers["Pragma"] = "no-cache"
req.headers["Expires"] = "0"
req.headers['Cache-Control'] = 'public, max-age=0'
return req