-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
501 lines (386 loc) · 16.5 KB
/
Copy pathserver.py
File metadata and controls
501 lines (386 loc) · 16.5 KB
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
"""Create server with routes to handle requests."""
from flask import (Flask, jsonify, render_template, request, flash, session)
from flask_login import login_user, logout_user, login_required, current_user
from model import connect_to_db, db
from jinja2 import StrictUndefined
import os
import requests
import json
import werkzeug.security
import copy
import crud
import helpers
app = Flask(__name__)
# the secret key is needed for flash and session to work
app.secret_key = "dev"
# This configuration option makes the Flask interactive debugger
# more useful (you should remove this line in production though)
app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = True
# configure a Jinja2 setting to make it throw errors for undefined variables
# by default it fails silently
app.jinja_env.undefined = StrictUndefined
YELP_FUSION_API_KEY = os.environ['YELP_FUSION_API_KEY']
# will have trouble running locally now, unless I add an ip address restriction for my local computer to Google Maps API
MAPS_JS_API_KEY = os.environ['MAPS_JS_API_KEY']
BASE_URL = 'https://api.yelp.com/v3/businesses'
@app.route('/')
def index():
"""Display homepage."""
url=f'https://maps.googleapis.com/maps/api/js?key={MAPS_JS_API_KEY}&v=weekly'
return render_template('index.html', url=url)
# ********************************
# User Routes
# ********************************
# register a user route
@app.route('/signup', methods=['POST'])
def signup():
"""Create an account for a new user."""
result = {
"success": False,
"message": "",
}
old_to_new_keys = {
'signupFirstName': 'first_name',
'signupLastName': 'last_name',
'signupUsername': 'username',
'signupPassword': 'password'
}
signup_data = helpers.rename_dict_keys(request.get_json(), old_to_new_keys)
first_name, last_name, username, password = list(signup_data.values())
hashed_password = werkzeug.security.generate_password_hash(password)
user = crud.get_user_by_username(username)
# if username taken
if user:
result["message"] = "That username is taken. Please try again."
return jsonify(result)
# password too short
if len(password) < 8:
result["message"] = "Your password must be at least 8 characters long."
return jsonify(result)
# username is unique and password long enough
new_user = crud.create_user(first_name,
last_name,
username,
hashed_password,)
if new_user:
db.session.add(new_user)
db.session.commit()
result["success"] = True
result["message"] = "Account created! Please log in."
return jsonify(result)
@app.route('/login', methods=['POST'])
def login():
"""Login a user.
Responds to frontend login form submission.
Checks for a user with the submitted username.
- if none is found, returns jsonified dictionary:
{
"user": None,
"success": False,
"message": "No user exists with that username.",
}
- if one is found, the submitted password is checked against the
database
- if the password is correct, returns the jsonified user:
{
"user": <the user object>,
"success": True,
"message": "",
}
- if password is incorrect,
- multiple users should not be found, because this is prevented at
user sign up
Args: none
Data payload should be a dictionary with username and password keys.
"""
result = {
"user": None,
"success": False,
"message": "",
}
old_to_new_keys = {
'loginUsername': 'username',
'loginPassword': 'password',
}
# var_names = ['username', 'password']
login_data = helpers.rename_dict_keys(request.get_json(), old_to_new_keys)
username, password = list(login_data.values())
count = crud.count_users_by_username(username)
# if no users found
if count == 0:
result["message"] = "No user exists with that username."
return jsonify(result)
# if one user found
user = crud.get_user_by_username(username)
# if password does NOT match
if werkzeug.security.check_password_hash(user.password, password) == False:
result["message"] = 'Username or password is incorrect. Please try again.'
return jsonify(result)
# if password does match
session["current_user_id"] = user.id
result["user"] = {
"id": user.id,
"first_name": user.first_name,
"last_name": user.last_name,
"username": user.username,
}
result["success"] = True
result["message"] = 'Success! You\'re now logged in.'
return jsonify(result)
@app.route('/logout')
# @login_required #Flask-Login
def logout():
"""Logout a user."""
# TODO: implement Flask-Login
# logout_user()
if "current_user_id" in session:
del session["current_user_id"]
result = {
"user": None,
"success": True,
"message": "User has been logged out"
}
return jsonify(result)
# TODO: verify that this 2.0 feature works
@app.route('/users/<id>', methods=['PUT'])
def updateUser(id):
result = {
"user": None,
"success": False,
"message": "",
}
profile_data = request.get_json()
user = crud.get_user_by_id(id)
if user:
updated_user = crud.update_user(user, profile_data)
# TODO: got user.verified from flask-sqlalchemy docs; am I using it correctly?
user.verified = True
db.session.commit()
result["success"] = True
result["message"] = "Account updated!"
return jsonify(result)
else:
result["message"] = "No user exists with that id."
return jsonify(result)
# TODO: KEEP?? - see alternate below
# TODO: NOTE that Drue approved of how I wrote the logic for this route
# (across all files, including crud.py and helpers.py)
@app.route('/users/<id>/feedbacks')
def getUserFeedbacks(id):
"""Get user's feedbacks.
Return a list of businesses with feedback given by a specific user.
"""
businesses_with_feedbacks = crud.get_feedbacks_by_user(id)
return jsonify(businesses_with_feedbacks)
# @app.route('/external/map.js', methods=['GET'])
# def get_google_map_script():
# url=f'https://maps.googleapis.com/maps/api/js?key={MAPS_JS_BACKEND_API_KEY}&v=weekly'
# response = requests.get(url)
# return response.content
# ********************************
# Business routes
# ********************************
# search for businesses
# TODO: add .json to the route? other?
@app.route('/businesses/search', methods=['GET'])
# @login_required #Flask-Login
def find_businesses():
"""Return from Yelp businesses in a user-provided zip code.
Gets the zip code from the query string and makes a request to Yelp for
restaurants in that area.
Returns a jsonified list of business dictionaries.
"""
# TODO: pull some logic out of this route into separate methods here
# in server.py or in helpers.py
# ********************************************************************
# set parameters for Yelp business search and execute search
# ********************************************************************
term = 'restaurants'
location = request.args.get('zipCode', '')
radius = 24000 # in meters; this is about 15 miles
# TODO: change the number of results to 25
limit = 16 # limit the number of results to return
# TODO: handle the situation where no zipCode is passed in
# TODO: handle the situation where invalid zipCode is passed in (use regex?)
payload = {"term": term, "location": location, "radius": radius, "limit": limit, }
headers = {"Authorization": f"Bearer {YELP_FUSION_API_KEY}"}
url = f"{BASE_URL}/search"
res = requests.get(url, params=payload, headers=headers)
search_results = res.json()
# ********************************************************************
# rename keys in dicts from Yelp search
# ********************************************************************
searched_businesses = [] # a list
old_to_new_keys = {
'id': 'yelp_id',
'name': 'place_name',
'coordinates': 'coordinates',
'display_phone': 'display_phone',
'location': 'location',
'image_url': 'photo',
}
for business in search_results['businesses']:
new_business = helpers.rename_dict_keys(business, old_to_new_keys)
searched_businesses.append(new_business)
# ********************************************************************
# get a list of unique yelp_ids represented in the Yelp search
# ********************************************************************
# set of unique yelp_ids
searched_yelp_ids = { business['yelp_id'] for business in searched_businesses }
# ********************************************************************
# attach list of feedback objects to list of searched businesses
# ********************************************************************
# create a dictionary of business dtbs objects with attached feedbacks
# (if any), each with yelp_id as the key
businesses_with_feedbacks = crud.get_businesses_with_feedbacks(searched_yelp_ids)
searched_businesses = helpers.match_feedbacks_with_businesses(
searched_businesses,
businesses_with_feedbacks)
# ********************************************************************
# create a dict for each feedback for each business returned from Yelp
# ********************************************************************
for business in searched_businesses:
feedbacks = []
for feedback_obj in business['feedback_objs']:
feedback = feedback_obj.as_dict()
feedbacks.append(feedback)
business['feedbacks'] = feedbacks
# delete database objs, bc they are not JSON serializable
if business.get('feedback_objs'):
del business['feedback_objs']
# ********************************************************************
# Aggregate the feedback for each business returned from Yelp.
# ********************************************************************
for business in searched_businesses:
business = helpers.aggregate_feedback(business)
return jsonify(searched_businesses)
# get business details from Yelp
# TODO: remove route if not being used
@app.route('/businesses/<yelp_id>')
def get_business_from_yelp(yelp_id):
"""Get details about a business."""
# ********************************************************************
# set parameters for Yelp business search and execute search
# ********************************************************************
id = request.args.get('id', '')
payload = {"locale": "en_US" }
headers = {"Authorization": f"Bearer {YELP_FUSION_API_KEY}"}
url = f"{BASE_URL}/{yelp_id}"
res = requests.get(url, params=payload, headers=headers)
business = res.json()
# ********************************************************************
# rename keys in dicts from Yelp search
# ********************************************************************
old_to_new_keys = {
'id': 'yelp_id',
'name': 'place_name',
'coordinates': 'coordinates',
'display_phone': 'display_phone',
'location': 'location',
'image_url': 'photo',
}
new_business = helpers.rename_dict_keys(business, old_to_new_keys)
# ********************************************************************
# get business from yelp by yelp id - result has feedback attached
# ********************************************************************
business_with_feedbacks = crud.get_business_by_yelp_id(yelp_id)
# attach id to new_business
# handle the case where there are no feedbacks (business_with_feedbacks returns None)
if business_with_feedbacks:
new_business["id"] = business_with_feedbacks.id
else:
new_business["id"] = None
# ********************************************************************
# create a dict for each feedback for the business returned from Yelp
# ********************************************************************
feedbacks = []
if business_with_feedbacks:
for feedback_obj in business_with_feedbacks.feedbacks:
feedback = feedback_obj.as_dict()
feedbacks.append(feedback)
new_business['feedbacks'] = feedbacks
# delete database objs, bc they are not JSON serializable
if new_business.get('feedback_objs'):
del business['feedback_objs']
# ********************************************************************
# Aggregate the feedback for each business returned from Yelp.
# ********************************************************************
new_business = helpers.aggregate_feedback(new_business)
return jsonify(new_business)
# ********************************
# Feedback routes
# ********************************
@app.route('/feedbacks', methods=['POST'])
def create_feedback():
"""Add user feedback for a restaurant to the database."""
result = {
"success": False,
"message": "",
}
feedback_data = request.get_json()
old_to_new_keys = {
'user_id': 'user_id',
'business_id': 'business_id',
'feedbackChairParkingChecked': 'chair_parking',
'feedbackRampChecked': 'ramp',
'feedbackAutoDoorChecked': 'auto_door',
'feedbackComment': 'comment',
}
feedback = helpers.rename_dict_keys(feedback_data, old_to_new_keys)
feedback = crud.create_feedback(feedback['user_id'], feedback['business_id'],
feedback['chair_parking'], feedback['ramp'], feedback['auto_door'],
feedback['comment'])
db.session.add(feedback)
db.session.commit()
result["success"] = True
result["message"] = "Feedback added"
return jsonify(result)
# ********************************************
# GENERATE BUSINESSES FOR DATABASE SEEDING
# ********************************************
# return a list of business dictionaries for the purpose of generating seed data
# TODO: add .json to the route? other?
@app.route('/businesses/generate')
def get_businesses_for_zip_code():
"""Return from Yelp businesses in a user-provided zip code.
Gets the zip code from the query string and makes a request to Yelp for
restaurants in that area.
Returns a jsonified list of business dictionaries.
"""
term = 'restaurants'
location = request.args.get('zipCode', '')
radius = 24000 # in meters; this is about 15 miles
# TODO: change the number of results to 25
limit = 50 # limit the number of results to return
# TODO: handle the situation where no zipCode is passed in
# TODO: handle the situation where invalid zipCode is passed in (use regex?)
payload = {"term": term, "location": location, "radius": radius, "limit": limit,}
headers = {"Authorization": f"Bearer {YELP_FUSION_API_KEY}"}
url = f"{BASE_URL}/search"
res = requests.get(url, params=payload, headers=headers)
search_results = res.json()
businesses = [] # a list
for business in search_results['businesses']:
new_business = {}
new_business['business_name'] = business.get('name', 'Unknown business name')
new_business['display_phone'] = business.get('display_phone', 'Unknown phone number')
yelp_id = business.get('id', None)
if yelp_id:
new_business['yelp_id'] = yelp_id
if business.get('location'):
bus_location = {"address1": business['location'].get('address1', 'Unknown address'),
"city": business['location'].get('city', 'Unknown city'),
"state": business['location'].get('state', 'Unknown state'),
"zip_code": business['location'].get('zip_code', 'Unknown zip code'),}
new_business['location'] = bus_location
if business.get('image_url'):
new_business['photo'] = business['image_url']
businesses.append(new_business)
return jsonify(businesses)
if __name__ == "__main__":
# connect to the database before app.run gets called
# if you don't do this, Flask won't be able to access your database
connect_to_db(app)
# app.debug = True
# app.run(host="0.0.0.0", debug=True)
app.run()