-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·309 lines (249 loc) · 9.58 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
import os
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_modus import Modus
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from flask_debugtoolbar import DebugToolbarExtension
from flask_migrate import Migrate
from sqlalchemy.exc import IntegrityError
from forms import UserForm, LoginForm, MessageForm
from decorators import ensure_correct_user
from sqlalchemy import or_
app = Flask(__name__)
if os.environ.get('ENV') == 'production':
app.config['DEBUG'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
else:
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/warbler_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or "it's a secret"
toolbar = DebugToolbarExtension(app)
modus = Modus(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from models import User, Message
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
login_manager.login_view = "users_login"
# Users routes
@app.route('/users', methods=["GET"])
def users_index():
search = request.args.get('q')
users = None
if search is None or 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(
'/signup', methods=[
"GET",
])
def users_new():
return render_template('users/signup.html', form=UserForm())
@app.route('/signup', methods=["POST"])
def users_create():
form = UserForm()
if form.validate():
try:
new_user = User(
username=form.username.data,
email=form.email.data,
password=User.hash_password(form.password.data),
header_image_url=form.header_image_url.data,
bio=form.bio.data,
location=form.location.data)
if form.image_url.data:
new_user.image_url = form.image_url.data
db.session.add(new_user)
db.session.commit()
login_user(new_user)
return redirect(url_for('root'))
except IntegrityError as e:
flash({'text': "Username already taken", 'status': 'danger'})
return render_template('users/signup.html', form=form)
@app.route('/login', methods=["GET"])
def users_login():
return render_template('users/login.html', form=LoginForm())
@app.route('/login', methods=["POST"])
def users_login_create():
form = LoginForm()
if form.validate():
found_user = User.authenticate(form.username.data, form.password.data)
if found_user:
login_user(found_user)
flash({
'text': f"Hello, {found_user.username}!",
'status': 'success'
})
return redirect(url_for('root'))
flash({'text': "Invalid credentials.", 'status': 'danger'})
return render_template('users/login.html', form=form)
@app.route('/logout')
@login_required
def users_logout():
logout_user()
flash({'text': "You have successfully logged out.", 'status': 'success'})
return redirect(url_for('users_login'))
@app.route('/users/<int:follower_id>/followers', methods=['POST'])
@login_required
def followers_create(follower_id):
followed = User.query.get_or_404(follower_id)
current_user.following.append(followed)
db.session.add(current_user)
db.session.commit()
return redirect(url_for('users_following', user_id=current_user.id))
@app.route('/users/<int:follower_id>/followers', methods=['DELETE'])
@login_required
def followers_destroy(follower_id):
followed = User.query.get_or_404(follower_id)
current_user.following.remove(followed)
db.session.add(current_user)
db.session.commit()
return redirect(url_for('users_following', user_id=current_user.id))
@app.route('/users/<int:user_id>/following', methods=['GET'])
@login_required
def users_following(user_id):
found_user = User.query.get_or_404(user_id)
return render_template(
'users/following.html', user=found_user, form=UserForm(obj=found_user))
@app.route('/users/<int:user_id>/followers', methods=['GET'])
@login_required
def users_followers(user_id):
found_user = User.query.get_or_404(user_id)
return render_template(
'users/followers.html', user=found_user, form=UserForm(obj=found_user))
@app.route('/users/<int:user_id>', methods=["GET"])
def users_show(user_id):
found_user = User.query.get_or_404(user_id)
return render_template(
'users/show.html', user=found_user, form=UserForm(obj=found_user))
# @app.route('/users/<int:user_id>/edit')
# @login_required
# @ensure_correct_user
# def users_edit(user_id):
# found_user = User.query.get_or_404(user_id)
# return render_template(
# 'users/edit.html',
# form=UserForm(obj=found_user),
# user_id=found_user.id)
@app.route('/users/<int:user_id>', methods=["PATCH"])
@login_required
@ensure_correct_user
def users_update(user_id):
found_user = User.query.get_or_404(user_id)
form = UserForm(request.form)
if form.validate():
if User.authenticate(found_user.username, form.password.data):
found_user.username = form.username.data
found_user.email = form.email.data
found_user.image_url = form.image_url.data or "/static/images/default-pic.png"
found_user.bio = form.bio.data
found_user.location = form.location.data
found_user.header_image_url = form.header_image_url.data
db.session.add(found_user)
db.session.commit()
return redirect(url_for('users_show', user_id=user_id))
flash({
'text': "Wrong password, please try again.",
'status': 'danger'
})
return redirect(url_for('users_show', user_id=user_id))
@app.route('/users/<int:user_id>', methods=["DELETE"])
@login_required
@ensure_correct_user
def users_destroy(user_id):
found_user = User.query.get_or_404(user_id)
db.session.delete(found_user)
db.session.commit()
return redirect(url_for('users_new'))
# Messages routes
@app.route('/users/<int:user_id>/messages', methods=["POST"])
@login_required
@ensure_correct_user
def messages_index(user_id):
form = MessageForm()
if form.validate():
new_message = Message(text=form.text.data, user_id=user_id)
db.session.add(new_message)
db.session.commit()
return redirect(url_for('users_show', user_id=user_id))
return render_template('messages/new.html', form=form)
@app.route('/users/<int:user_id>/messages/new')
@login_required
@ensure_correct_user
def messages_new(user_id):
return render_template('messages/new.html', form=MessageForm())
@app.route('/users/<int:user_id>/messages/<int:message_id>', methods=["GET"])
def messages_show(user_id, message_id):
found_message = Message.query.get_or_404(message_id)
return render_template('messages/show.html', message=found_message)
@app.route(
'/users/<int:user_id>/messages/<int:message_id>', methods=["DELETE"])
@login_required
@ensure_correct_user
def messages_destroy(user_id, message_id):
found_message = Message.query.get_or_404(message_id)
db.session.delete(found_message)
db.session.commit()
return redirect(url_for('users_show', user_id=user_id))
@app.route('/likes', methods=["POST"])
def like():
"""Like/unlike a message; this is to be used from AJAX so it does not return a full page."""
isLike = request.form['data']
message_id = request.form['message_id']
if isLike == 'true':
message = Message.query.get_or_404(message_id)
current_user.likes.append(message)
db.session.add(current_user)
db.session.commit()
return "liked" # 200 OK
else:
message = Message.query.get_or_404(message_id)
current_user.likes.remove(message)
db.session.add(current_user)
db.session.commit()
return "unliked"
@app.route('/users/<int:user_id>/likes', methods=["GET"])
def like_messages_show(user_id):
found_user = User.query.get_or_404(user_id)
return render_template(
'users/like.html',
user=found_user,
messages=found_user.likes,
form=UserForm(obj=found_user))
@app.route('/')
def root():
messages = []
if current_user.is_authenticated:
followings = [f.id for f in current_user.following]
messages = Message.query.filter(
or_(
Message.user_id.in_(followings),
Message.user_id == current_user.id)).order_by(
Message.timestamp.desc()).limit(100).all()
return render_template(
'home.html', messages=messages, current_user=current_user)
# https://stackoverflow.com/questions/34066804/disabling-caching-in-flask
@app.after_request
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404