-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
204 lines (167 loc) · 6.22 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
from flask import Flask, redirect, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy.ext.automap import automap_base
import simplejson as json
import os
# Set up flask and db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('CLEARDB_DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_POOL_RECYCLE'] = 59
db = SQLAlchemy(app)
Base = automap_base()
Base.prepare(db.engine, reflect = True)
# Prepping both tables
restaurant = Base.classes.restaurant
category = Base.classes.category
# Home route
@app.route("/")
def home():
return render_template("index.html")
####################################
# API route to query restaurant data
####################################
@app.route("/api/<city>/<clientTime>/<attributes>", methods = ['GET'])
def data(city='', clientTime='0', attributes=[]):
# Convert the variables passed from JSON stringify
clientTime = json.loads(clientTime)
attributes = json.loads(attributes)
# Convert the day to a string and print the value
if clientTime['day'] == 0:
day = 'Sunday'
elif clientTime['day'] == 1:
day = 'Monday'
elif clientTime['day'] == 2:
day = 'Tuesday'
elif clientTime['day'] == 3:
day = 'Wednesday'
elif clientTime['day'] == 4:
day = 'Thursday'
elif clientTime['day'] == 5:
day = 'Friday'
elif clientTime['day'] == 6:
day = 'Saturday'
# Convert clientTime to minutes
clientTimeM = clientTime['h']*60 + clientTime['m']
# Select statement for all the desired columns
sel_category = [
category.Category_id,
category.Category
]
# Construct the query
query_category = db.session.query(*sel_category)
# Convert the list of queries to a dictionary with the key as the
# category and the value as the category name this will be used
# later to convert the comma separated category ids to a list of
# categories
category_dict = {row[0] : row[1] for row in query_category.all()}
# Select statement for all the desired columns
sel_restaurant = [
restaurant.Name,
restaurant.Address,
restaurant.Latitude,
restaurant.Longitude,
restaurant.Stars,
restaurant.Category_ids
]
# Construct the initial query
query_restaurant = db.session.query(*sel_restaurant) \
.filter(restaurant.City == city)
for attribute in attributes:
if attribute['name'] == 'OpenNow':
# If the row represents the openNow checkbox
if attribute['value'] == True:
# If the user only wants restaurants that are currently open
#
# Check that the client time is within the closing and
# opening time that the restaurant has listed for today
# and add it to the query
query_restaurant = query_restaurant \
.filter(getattr(restaurant, f'{day}_open') \
<= clientTimeM) \
.filter(getattr(restaurant, f'{day}_close') \
>= clientTimeM)
else:
if attribute['value'] == True:
# If the user checked the checkbox get the column name from
# the name key and only select restaurants that have a true
# value in that column
column = attribute['name']
query_restaurant = query_restaurant \
.filter(getattr(restaurant,column) == True)
# Empty list to append results from the restaurant table to
map_data = []
latitudes = []
longitudes = []
latitude_avg = 0
longitude_avg = 0
if len(query_restaurant.all()) == 0:
# If there are no results return 204 no content error
return jsonify(
map_data=map_data,
latitude_avg=latitude_avg,
longitude_avg=longitude_avg
)
else:
# Return the results found
for row in query_restaurant.all():
# Split the category ids on comma then replace each with
# corresponding category from the dictionary of categories
category_ids = row[5].split(',')
categories = [category_dict.get(int(value)) for value in category_ids]
# Append each row in the result as a dictionary
map_data.append({
'Name': row[0],
'Address': row[1],
'Latitude': row[2],
'Longitude': row[3],
'Stars': row[4],
'Categories': categories
})
latitudes.append(row[2])
longitudes.append(row[3])
# Calculating the center of the map for map.js
latitude_avg = (max(latitudes) + min(latitudes))/2
longitude_avg = (max(longitudes) + min(longitudes))/2
# Return two JSON separate objects
return jsonify(
map_data=map_data,
latitude_avg=latitude_avg,
longitude_avg=longitude_avg
)
#############################################
# API route to return a json of unique cities
#############################################
@app.route("/api/cityList", methods=['GET'])
def cityList():
# Empty list to store the results in
results = []
# Query for all the unique cities
query=db.session.query(restaurant.City).distinct(restaurant.City)
# Append results to the empty list
for row in query.all():
results.append(row[0])
# Return the results as JSON
return jsonify(results)
############################################
# Route to display information about the app
############################################
@app.route("/about")
def about():
return render_template("about.html")
###########################
# Contact information route
###########################
@app.route("/contact")
def contact():
return render_template("contact.html")
###########################
# API key route
###########################
@app.route("/key", methods=['GET'])
def key():
return jsonify(os.environ.get('mapboxApiKey'))
if __name__ == "__main__":
app.run(debug=False)