-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
350 lines (315 loc) · 12.5 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
# app.py
# Created by Megan Shum & Maxine Hood & Mina Hattori
# CS304-Final project
# This file runs the app.
#!/usr/local/bin/python2.7
from flask import (Flask, render_template, make_response, url_for, request,
redirect, flash, session, send_from_directory, jsonify)
from werkzeug import secure_filename
app = Flask(__name__)
import bcrypt
import sys,os,random
import dbconn2
import profops
import imghdr
import time
import uploadops
import accounts
import newsfeedOps
import searchops
app.secret_key = 'your secret here'
# replace that with a random key
app.secret_key = ''.join([ random.choice(('ABCDEFGHIJKLMNOPQRSTUVXYZ' +
'abcdefghijklmnopqrstuvxyz' +
'0123456789'))
for i in range(20) ])
# This gets us better error messages for certain common request errors
app.config['TRAP_BAD_REQUEST_ERRORS'] = True
#-------------------------------------------------------------------------
# All pages and funcitons for accounts. (Home, Login, Register, logout)
#-------------------------------------------------------------------------
# Displays home page
@app.route('/')
def home():
return render_template('home.html',
title='Foodies')
# Process login form
@app.route('/login/', methods=['GET', 'POST'])
def loginProcess():
# When get, return empty login page
if request.method == 'GET':
if 'username' in session:
return redirect(url_for('newsfeed'))
return render_template('login.html',
title='Login')
else:
username = request.form['username']
passwd = request.form['passwd']
conn = dbconn2.connect(DSN)
# If valid username and password
if (accounts.validUsername(conn, username)):
storedHash = accounts.getHashedPassword(conn, username)
if(bcrypt.hashpw(passwd.encode('utf-8'), storedHash.encode('utf-8')) == storedHash.encode('utf-8')):
# Save username to the session
session['username'] = username
return redirect(url_for('newsfeed'))
else:
# bad password
flash("Login failed. Please try again")
return render_template('login.html',
title='Login')
else:
# bad username
flash("Login failed. Please try again")
return render_template('login.html',
title='Login')
# Function logs out user and returns to the login page
@app.route('/logout/')
def logout():
session.pop('username', None)
return redirect(url_for('loginProcess'))
# Displays the register page
@app.route('/register/')
def register():
return render_template('register.html',
title='Register',
script=url_for('registerProcess'))
# Process register form
@app.route('/register/', methods=['POST'])
def registerProcess():
# When get, return empty login page
if request.method == 'GET':
return register()
else:
name = request.form['name']
email = request.form['email']
username = request.form['username']
passwd = request.form['passwd']
comPasswd = request.form['comPasswd']
# Sends back to register page if not all the fields were filled in.
if((name == "") or (email == "") or (username == "") or (passwd == "") or (comPasswd == "")):
flash("Please fill out all fields")
return register()
conn = dbconn2.connect(DSN)
# Checks for available username
if (accounts.validUsername(conn, username)):
flash("Username is taken")
return register()
# Checks that password matches
if (passwd != comPasswd):
flash("Passwords do not match")
return register()
# Hash password and register new account
hashed = bcrypt.hashpw(passwd.encode('utf-8'), bcrypt.gensalt())
accounts.registerUser(conn, username, hashed, name, email)
flash("Registration successful")
return redirect(url_for('loginProcess'))
#-------------------------------------------------------------------------
# All pages and funcitons for photos
#-------------------------------------------------------------------------
# Takes the upload data and saves image to database.
@app.route('/upload/', methods = ['GET', 'POST'])
def upload():
# Check for logged in user
if 'username' not in session:
flash("Please login")
return redirect(url_for('loginProcess'))
else:
if request.method == 'GET':
return render_template('upload.html',
profuser = session['username'])
else:
try:
username = session['username']
description = request.form['description'] # may throw error
location = request.form['location']
time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
f = request.files['pic']
mime_type = imghdr.what(f.stream)
if mime_type != 'jpeg':
raise Exception('Please upload a jpeg image')
# generating a unique filename with the use of timestamp
file = f.filename.split('.')[0]+time_stamp+".jpeg"
pic = secure_filename(str(file))
pathname = 'images/'+ pic
f.save(pathname) # saves the contents in a temporarily in the images folder
flash('Upload successful')
conn = dbconn2.connect(DSN)
uploadops.uploadPost(conn, username, description, location, time_stamp, pic)
return render_template('upload.html',
src=url_for('pic',fname=pic),
profuser = session['username']
)
except Exception as err:
flash('Upload failed {why}'.format(why=err))
return render_template('upload.html',
profuser = session['username'])
# Renders images by file name
@app.route('/images/<fname>')
def pic(fname):
f = secure_filename(fname)
mime_type = f.split('.')[-1]
val = send_from_directory('images',f)
return val
#-------------------------------------------------------------------------
# All pages and funcitons for displaying posts (Profile, newsfeed, explore, search)
#-------------------------------------------------------------------------
# Displays the profile for a given username
@app.route('/profile/<username>', methods = ['GET','POST'])
def profile(username):
# Check for logged in user
if 'username' not in session:
flash("Please log in")
return redirect(url_for('loginProcess'))
else:
conn = dbconn2.connect(DSN)
pics = profops.retrievePics(conn, username)
numPosts = profops.numPosts(conn, username)
# Get data for displayal on profile page
if request.method == 'GET':
followers = profops.getFollow(conn, username)
following = profops.getFollowing(conn, username)
isFollowing = profops.isFollowing(conn, session['username'], username)
notUser = True
# Check for user's own profile
if (session['username'] == username):
notUser = False
return render_template('profile.html',
username = username,
followers = followers,
following = following,
pics = pics,
follow = isFollowing,
notUser = notUser,
numPosts = numPosts,
profuser = session['username'])
else:
isfollowing = profops.isFollowing(conn, session['username'], username)
followers = profops.getFollow(conn, username)
following = profops.getFollowing(conn, username)
return render_template('profile.html',
username = username,
followers = followers,
following = following,
pics = pics,
follow = isfollowing,
notUser = True,
numPosts = numPosts,
profuser = session['username'])
# Searches for a username and displays that profile
@app.route('/search/', methods = ["POST"])
def search():
if 'username' in session:
if request.method == "POST":
search = request.form['search']
# Return to newsfeed
if search == "":
return redirect(url_for('newsfeed'))
else:
# Redirect to user's profile
conn = dbconn2.connect(DSN)
if searchops.searchExists(conn, search):
return redirect(url_for('profile', username = search))
# Return to newsfeed
else:
return redirect(url_for('newsfeed',profuser = session['username'] ))
else:
flash("Please log in")
return redirect(url_for('loginProcess'))
# Displays the Newsfeed page
@app.route('/newsfeed/', methods=['GET', 'POST'])
def newsfeed():
if 'username' in session:
# Display newsfeed
if request.method == 'GET':
username = session['username']
conn = dbconn2.connect(DSN)
# Get photos from people you follow
information = newsfeedOps.retrievePics(conn, username)
# Renders page with photos
if (information != None):
return render_template ('newsfeed.html',username = username, posts = information, profuser = session['username'])
# Renders page without photos
else:
flash("Follow people to see pictures on your Newsfeed!")
return render_template('newsfeed.html', username = username, posts = None, profuser = session['username'])
# Adds comment to post
else:
username = session['username']
comment = request.form['comment']
time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
post_id = request.form['post_id']
conn = dbconn2.connect(DSN)
# Add comment to database
newsfeedOps.addComment(conn, username, post_id, comment, time_stamp)
return redirect(url_for('newsfeed', profuser = session['username']))
else:
return redirect(url_for('loginProcess'))
# Display the explore page
@app.route('/explore/', methods = ['GET'])
def explore():
# if logged in
if 'username' in session:
conn = dbconn2.connect(DSN)
# Get the top posts in the database
pics = newsfeedOps.getExplorePosts(conn)
return render_template('explore.html', pics=pics, profuser = session['username'])
else:
flash("Please log in")
return redirect(url_for('loginProcess'))
#-------------------------------------------------------------------------
# Ajax function
#-------------------------------------------------------------------------
# Ajax function for liking a post
@app.route('/likePostAjax/', methods = ['POST'])
def likePostAjax():
conn = dbconn2.connect(DSN)
username = session['username']
post_id = request.form.get('post_id')
# update the likes for the post
newsfeedOps.updateLikes(conn,post_id,username)
# get the new number movie information
newLikes = newsfeedOps.getnewLikes(conn,post_id)
return jsonify({"likes": newLikes})
# Ajax function for unliking a post
@app.route('/unlikePostAjax/', methods = ['POST'])
def unlikePostAjax():
conn = dbconn2.connect(DSN)
username = session['username']
post_id = request.form.get('post_id')
# update thes likes for the post
newsfeedOps.updateUnlikes(conn,post_id,username)
# get the new number movie information
newLikes = newsfeedOps.getnewLikes(conn,post_id)
return jsonify({"likes": newLikes})
# Ajax function for following a user
@app.route('/followUserAjax/', methods = ['POST'])
def followUserAjax():
conn = dbconn2.connect(DSN)
username = session['username']
profuser = request.form.get('username')
# Add follow to database and get new followers count
profops.follow(conn, username, profuser)
newfollowers = profops.getFollow(conn, profuser)
return jsonify({"followers": newfollowers})
# Ajax function for unfollowing a user
@app.route('/unfollowUserAjax/', methods = ['POST'])
def unfollowUserAjax():
conn = dbconn2.connect(DSN)
username = session['username']
profuser = request.form.get('username')
# Delete following from the database and return new follower count
profops.unfollow(conn, username, profuser)
newfollowers = profops.getFollow(conn, profuser)
return jsonify({"followers": newfollowers})
if __name__ == '__main__':
if len(sys.argv) > 1:
# arg, if any, is the desired port number
port = int(sys.argv[1])
assert(port>1024)
else:
port = os.getuid()
DSN = dbconn2.read_cnf()
DSN['db'] = 'mmm_db'
app.debug = True
app.run('0.0.0.0',port)