forked from joshedgcomb/buy5c
/
views.py
481 lines (389 loc) · 16.6 KB
/
views.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import re
import io
from flask import (
render_template,
redirect,
request,
url_for,
g,
flash,
send_file,
abort
)
from flask.ext.login import current_user, login_user, logout_user
from models import *
from app import app, lm, pwd_context, app_session
from datetime import datetime
session = app_session
# Some basic regular expressions to match 5C email addresses
# These are not yet actually used, so you can use literally
# any string you want when making a new account. It doesn't
# even have to be an actual email address.
pomona_regex = re.compile(r"[\w.]+@[\w.]*pomona.edu")
cmc_regex = re.compile(r"[\w.]+@[\w.]*cmc.edu")
hmc_regex = re.compile(r"[\w.]+@[\w.]*hmc.edu")
scripps_regex = re.compile(r"[\w.]+@[\w.]*scripps.edu")
pitzer_regex = re.compile(r"[\w.]+@[\w.]*pitzer.edu")
# Used to check if a user's price is a number
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def get_listings(category=None, page_size=24, page_offset=0, user_id=None, listing_ids=None):
if listing_ids:
listings = []
for x in listing_ids:
listings.append(session.query(Listing).get(x))
return listings
# for user specific listing queries, this can only return all of a user's listings
if user_id:
user = session.query(User).get(user_id)
listings = user.listings
return listings.reverse()
if category is None:
listings = session.query(Listing).order_by(Listing.id.desc()).limit(page_size).offset(page_size*page_offset).all()
else:
category_id = session.query(Category).filter(Category.name == category).first().id
listings = session.query(Listing).filter(Listing.category_id == category_id).order_by(Listing.id.desc()).limit(page_size).offset(page_size*page_offset).all()
return listings
@app.route('/get_image/<int:listing_id>')
def get_image(listing_id):
image_binary = session.query(Listing).get(listing_id).image
if image_binary is None:
return None
return send_file(io.BytesIO(image_binary))
# Before every request that's made, this will run, setting
# flask's global variable g.user to the user currently logged
# in from the computer making the request, allowing for easy
# access.
@app.before_request
def before_request():
g.user = current_user
global session
session = app.config['SESSION']
session.rollback()
@app.after_request
def after_request(response):
response.headers['Cache-Control'] = 'public, max-age=0'
return response
# function telling the login manager how to load a user
@lm.user_loader
def load_user(id):
return session.query(User).get(int(id))
# The basic login page and function.
@app.route('/login', methods=['GET', 'POST'])
def login():
# If a user is already logged in. is_authenticated is a function
# of the User class in models.py
if g.user.is_authenticated():
return render_template('index.html',
message='A user is already logged in.',
email=g.user.email,
listings=get_listings())
# If the user is sending information (i.e. trying to log in),
# checks the selected email against the users in the database.
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
# queries the database for a user with the email submitted
user = session.query(User).filter(User.email == email).first()
# if the user was in the database and the password matches,
# logs the user in and returns a message.
if user is not None and pwd_context.verify(password, user.password):
login_user(user)
return render_template('index.html',
message='Login was successful.',
email=user.email,
listings=get_listings())
return render_template('index.html',
message='Email or password invalid. Please try again.',
listings=get_listings())
# returns login form if request method was GET
return render_template('login.html')
# The form and function for creating a new account.
@app.route('/register', methods=['GET', 'POST'])
def register():
# if a user is already logged in
if g.user.is_authenticated():
return render_template('index.html',
message='Please logout before attempting to create a new_account.',
email=g.user.email,
listings=get_listings())
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = session.query(User).filter(User.email == email).first()
if user is not None:
return render_template('index.html',
message='An account with that email already exists. If you have forgotten your password,'
+ ' go to "buy5c.com/forgot_password" to find out how to reset it.',
listings=get_listings())
# if no user with that email exists, creates one and adds it to the database
else:
password = pwd_context.encrypt(password)
user = User(email, password)
session.add(user)
session.commit()
return render_template('index.html',
message='Account successfully created.',
listings=get_listings())
return render_template('register.html')
# sell page and function: not yet implemented
@app.route('/sell', methods=['GET', 'POST'])
def sell():
if not g.user.is_authenticated():
return render_template('index.html',
message='You must be logged in to sell an item.',
listings=get_listings())
if request.method == 'POST':
title = request.form['title']
description = request.form['description']
category = request.form['category']
price = request.form['price']
image = None
if 'image' in request.files:
image_file = request.files['image'].read()
image = buffer(image_file)
if image_file == '':
image = None
if len(title) == 0:
return render_template('sell.html',
message='Please include a title for your item.',
email=g.user.email)
if len(description) == 0:
return render_template('sell.html',
message='Please include a description for your item.',
email=g.user.email)
if len(category) == 0:
return render_template('sell.html',
message='Please select a category for your item.',
email=g.user.email)
if not is_number(price):
return render_template('sell.html',
message='Please include a price for your item. Note: it must be a number',
email=g.user.email)
category_id = session.query(Category).filter(Category.name == category).first()
listing = Listing(title, description, category_id, g.user.id, datetime.utcnow(), price, image)
session.add(listing)
session.commit()
return render_template('index.html',
message='Listing successfully created',
email=g.user.email,
listings=get_listings())
return render_template('sell.html', email=g.user.email)
#
@app.route("/logout")
def logout():
logout_user()
flash("Logged out.")
return redirect('/index')
@app.route('/')
@app.route('/index')
def index():
if g.user.is_authenticated():
return render_template('index.html',
email=g.user.email,
listings=get_listings(),
active='Everything')
return render_template('index.html',
listings=get_listings(),
active='Everything')
@app.route('/a_a/')
def a_a():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Apparel/Accessories')
return render_template('index.html',
active='Apparel/Accessories')
@app.route('/appliances')
def appliances():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Appliances')
return render_template('index.html',
active='Appliances')
@app.route('/books')
def books():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Books')
return render_template('index.html',
active='Books')
@app.route('/electronics')
def electronics():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Electronics')
return render_template('index.html',
active='Electronics')
@app.route('/furniture')
def furniture():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Furniture')
return render_template('index.html')
@app.route('/mmg')
def mmg():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Movies, Music, and Games')
return render_template('index.html',
active='Movies, Music, and Games')
@app.route('/tickets')
def tickets():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Tickets')
return render_template('index.html',
active='Tickets')
@app.route('/other')
def other():
if g.user.is_authenticated():
return render_template('index.html',
username=g.user.email,
active='Miscellaneous')
return render_template('index.html',
active='Miscellaneous')
@app.route('/listing/<listing_id>')
def listing(listing_id):
listing = session.query(Listing).get(listing_id)
if listing is None:
abort(404)
if g.user.is_authenticated():
if listing.image is None:
return render_template('listing.html',
email=g.user.email,
user_id=g.user.id,
listing_user_id=listing.user_id,
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price)
else:
return render_template('listing.html',
email=g.user.email,
user_id=g.user.id,
listing_user_id=listing.user_id,
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price,
image=listing.image)
else:
if listing.image is None:
return render_template('listing.html',
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price)
else:
return render_template('listing.html',
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price,
image=listing.image)
@app.route('/listing/<listing_id>/edit', methods=['GET', 'POST'])
def edit_listing(listing_id):
listing = session.query(Listing).get(listing_id)
if listing is None:
return abort(404)
if not g.user.is_authenticated():
return render_template('listing.html',
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price,
image=listing.image,
message='You must be logged in to edit your listing.')
if g.user.id != listing.user_id:
return render_template('listing.html',
email=g.user.email,
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price,
image=listing.image,
message='Only the creator of this listing may edit it.')
if request.method == 'GET':
return render_template('edit_listing.html',
listing_id=listing_id,
title=listing.title,
description=listing.description,
price=listing.price,
image=listing.image)
elif request.method == 'POST':
title = request.form['title']
description = request.form['description']
category = request.form['category']
price = request.form['price']
image = None
if 'image' in request.files:
image_file = request.files['image'].read()
if image_file != '':
image = buffer(image_file)
listing.image = image
if title != '':
listing.title = title
if description != '':
listing.description = description
if category != '':
category_id = session.query(Category).filter(Category.name == category).first()
listing.category_id = category_id
if price != '' and is_number(price):
listing.price = price
session.commit()
return redirect(url_for('listing', listing_id=listing_id))
@app.route('/account')
def account():
if g.user.is_authenticated():
listings = get_listings(user_id=g.user.id)
if listings is not None:
return render_template('account.html',
email=g.user.email,
listings=listings
)
else:
return render_template('account.html',
email=g.user.email,
message="No listings found.")
return redirect(url_for('login'))
@app.route('/search', methods=['POST'])
def search():
if g.user.is_authenticated():
terms = request.form['terms']
query_string = "select * from listing where tsv @@ plainto_tsquery('english', :terms)"
listings = session.execute(query_string, {'terms':terms}).fetchall()
listing_ids = []
for listing in listings:
listing_ids.append(listing.id)
listing_ids.reverse()
count = len(listings)
return render_template('index.html',
email=g.user.email,
listings=get_listings(listing_ids=listing_ids),
message="Search returned " + str(count) + " listings.")
@app.route('/about')
def about():
return False
@app.route('/terms')
def terms():
return False
@app.route('/contact')
def contact():
return False
@app.route('/feedback')
def feedback():
return False
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404