-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
285 lines (198 loc) · 8.45 KB
/
server.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
from flask import Flask, request, render_template, flash, redirect, session, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from jinja2 import StrictUndefined
import os
import bcrypt
from model import Genre, Museum, Trip, User, connect_to_db, db
from request_yelp import get_restaurant
from favorited_genres import get_favorited_genres_all, get_favorited_genres_user
app = Flask(__name__)
app.jinja_env.undefined = StrictUndefined
app.jinja_env.auto_reload = True
app.secret_key = "ABC"
@app.route('/')
def go_home():
"""Goes to the homepage. Homepage has user either login or register."""
# if session.has_key("user_id"):
# return redirect("/users/%s" % session['user_id'])
return render_template("index.html")
@app.route("/favorite_genres.json")
def get_genres_favorited_by_users():
"""Return data about genres favorited."""
trips_favorited_all = Trip.query.filter_by(favorited=True).all()
genre_names_all, counts_all = get_favorited_genres_all(trips_favorited_all)
data_dict = {
"labels": genre_names_all,
"datasets": [
{
"data": counts_all,
"backgroundColor": [
"#FF6384",
"#36A2EB",
"#FFCE56",
"#cc99ff",
"#0066ff",
"#009999",
"#ccff33",
"#990099"
],
"hoverBackgroundColor": [
"#FF6384",
"#36A2EB",
"#FFCE56",
"#cc99ff",
"#0066ff",
"#009999",
"#ccff33",
"#990099"
]
}]
}
return jsonify(data_dict)
@app.route('/register', methods=['POST'])
def register_process():
"""Process registration."""
# Get form variables
name = request.form["name"]
email = request.form["email"]
password = request.form["password"]
password_hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
if User.query.filter_by(email=email).first():
flash("User %s already exists." % email)
return redirect("/")
new_user = User(name=name, email=email, password=password_hashed)
db.session.add(new_user)
db.session.commit()
session["user_id"] = new_user.user_id
flash("User %s added." % email)
return redirect("/users/%s" % new_user.user_id)
@app.route('/login')
def login_form():
"""Show login form."""
return render_template("login_form.html")
@app.route('/login_process', methods=['POST'])
def login_process():
"""Process login."""
# Get form variables
email = request.form["email"]
password = request.form["password"]
password_hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
user = User.query.filter_by(email=email).first()
password_to_check = user.password
if not user:
flash("No such user")
return redirect("/login")
# if (bcrypt.checkpw(password.encode('utf-8'), password_hashed)) == False:
if (bcrypt.checkpw(password_to_check, password_hashed)) == False:
flash("Incorrect password")
return redirect("/login")
session["user_id"] = user.user_id
flash("Logged in")
return redirect("/users/%s" % user.user_id)
@app.route('/logout')
def logout():
"""Log out."""
if session.has_key('user_id'):
del session["user_id"]
flash("Logged Out.")
return redirect("/")
@app.route('/users/<int:user_id>')
def show_profile(user_id):
"""Shows profile information and trips for user."""
user = User.query.filter_by(user_id=user_id).first()
trips = Trip.query.filter_by(user_id=user_id).all()
return render_template("user_profile.html", user=user, trips=trips)
@app.route('/users/comparative_favorite_genres.json')
def get_comparative_genres_favorited():
"""Return data about genres favorited by all users and user."""
trips_favorited_all = Trip.query.filter_by(favorited=True).all()
genre_names_all, counts_all = get_favorited_genres_all(trips_favorited_all)
user_id = session['user_id']
trips_favorited_user = Trip.query.filter_by(favorited=True, user_id=user_id).all()
counts_user = get_favorited_genres_user(trips_favorited_user)
data_dict = {
"labels": genre_names_all,
"datasets": [
{
"label": "All users",
"backgroundColor": "rgba(0, 0, 255, 0.3)",
"borderColor": "#6600ff",
"data": counts_all
},
{
"label": "You",
"backgroundColor":"rgba(0, 255, 0, 0.3)",
"borderColor":"#336600",
"data": counts_user
}
]
}
return jsonify(data_dict)
@app.route('/images')
def show_images():
"""Shows user images to choose from, to establish his/her art genre."""
genres = Genre.query.all()
return render_template("art.html", genres=genres)
@app.route('/itinerary/<genre_code>', methods=["GET"])
def show_itinerary(genre_code):
"""Give an itinerary including trips to a museum and eatery."""
museum = Museum.query.filter_by(genre_code=genre_code).first()
location = museum.address1 + museum.address2
resp = get_restaurant(location)
if resp == None:
return "An error has occurred."
restaurant_id, restaurant_name, restaurant_location1, restaurant_location2, restaurant_coordinates, restaurant_image = resp
print resp
restaurant_latitude = float(restaurant_coordinates['latitude'])
restaurant_longitude = float(restaurant_coordinates['longitude'])
if None in list(resp):
return "An error has occurred"
if 'user_id' in session:
user_id = session["user_id"]
trip = Trip(user_id=user_id,
museum_id=museum.museum_id,
restaurant_id=restaurant_id,
restaurant_name=restaurant_name,
restaurant_longitude=restaurant_longitude,
restaurant_latitude=restaurant_latitude)
db.session.add(trip)
db.session.commit()
return render_template("itinerary.html", museum=museum,
restaurant_name=restaurant_name,
restaurant_location1=restaurant_location1,
restaurant_location2=restaurant_location2,
restaurant_image=restaurant_image,
trip=trip)
@app.route('/map/from_profile_page', methods=["POST"])
def get_map_from_profile_page():
"""Give a map and directions with starting and ending points chosen by user."""
user_location = request.form.get("user_location")
trip_id = request.form.get("trip_id")
trip = Trip.query.filter_by(trip_id=trip_id).first()
key = os.environ['GOOGLE_API_DIRECTIONS_KEY']
return render_template("map.html", key=key, trip=trip, user_location=user_location)
@app.route('/map/<int:trip_id>', methods=["POST"])
def get_map(trip_id):
"""Give a map and directions with starting and ending points chosen by user."""
user_location = request.form.get("user_location")
trip = Trip.query.filter_by(trip_id=trip_id).first()
key = os.environ['GOOGLE_API_DIRECTIONS_KEY']
return render_template("map.html", key=key, trip=trip, user_location=user_location)
@app.route('/favorite.json', methods=["POST"])
def mark_favorite_status():
"""Update favorites table as to whether they have a favorited trip."""
trip_id = request.form.get("trip_id")
favorited = request.form.get("favorited")
trip = Trip.query.filter_by(trip_id=trip_id).first()
trip.favorited = favorited
db.session.commit()
response = { 'trip_id': trip_id, 'favorited': favorited}
return jsonify(response)
if __name__ == "__main__":
connect_to_db(app)
# We have to set debug=True here, since it has to be True at the
# point that we invoke the DebugToolbarExtension
app.debug = False
# Use the DebugToolbar
DebugToolbarExtension(app)
app.run(host="0.0.0.0")