/
server.py
259 lines (170 loc) · 7.18 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
from jinja2 import StrictUndefined
from flask import Flask, render_template, request, flash, redirect, session, jsonify
from sqlalchemy import desc
from datetime import datetime
import os
# from flask_debugtoolbar import DebugToolbarExtension
from model import connect_to_db, db, Restaurant, Offer
import requests
app = Flask(__name__)
app.secret_key = "b_xd3xf9095~xa68x90E^O1xd3R"
app.jinja_env.undefined = StrictUndefined
@app.route("/", methods=["GET"])
def index():
"""Show homepage."""
return render_template("homepage.html")
@app.route("/map")
def search_location():
"""Search for your location on the map."""
# Get user input from the search form
query = request.args.get("location")
req_tom = requests.get(f"https://api.tomtom.com/search/2/search/{query}.json?key=UEMHJeLAHMvvGsWGtxGl2NB9hNZXtpsm")
search_results = req_tom.json()
first_result = search_results.get("results")[1]
lat_lon = first_result.get("position")
return lat_lon
@app.route("/restaurant-object")
def get_restaurants_as_json():
"""Query database for restaurant info and send as JSON response."""
# Query database and create dictionary.
restaurants = Restaurant.query.options(db.joinedload('offers')).all()
rests = {}
for rest in restaurants:
rests[rest.name] = {'street_address': rest.street_address,
'city': rest.city,
'name': rest.name,
'state': rest.state,
'zipcode': rest.zipcode,
'email': rest.email}
if rest.offers:
offers = rest.offers
first_offer = offers[0]
rests[rest.name]['offer'] = first_offer.item
if not rest.offers:
rests[rest.name]['offer'] = " No current offers"
# Turn address into lat/lon using TomTom API.
for rest in rests.values():
rest["address"] = f"{rest['street_address']} {rest['city']}, {rest['state']} {rest['zipcode']}"
query = rest["address"]
req_tom = requests.get(f"https://api.tomtom.com/search/2/search/{query}.json?key=UEMHJeLAHMvvGsWGtxGl2NB9hNZXtpsm")
search_results = req_tom.json()
first_result = search_results.get("results")[1]
lat_lon = first_result.get("position")
# Update dictionary with lat/lon
rest["coordinate"] = [lat_lon["lon"], lat_lon["lat"]]
return jsonify(rests)
@app.route("/restaurant", methods=["GET"])
def show_login_form():
"""Show login form or registration button for restaurants."""
restaurant_id = session.get("restaurant_id")
if restaurant_id:
return redirect(f"/restaurant-dashboard/{restaurant_id}")
return render_template("restaurant-login.html")
@app.route("/restaurant", methods=["POST"])
def handle_login():
"""Login a restaurant user."""
email = request.form.get("email")
password = request.form.get("password")
restaurant = Restaurant.query.filter_by(email=email).first()
if not restaurant:
flash(f"No account with {email}.")
return redirect("/restaurant")
if not restaurant.check_password(password):
flash("Incorrect password.")
return redirect("/restaurant")
session["restaurant_id"] = restaurant.id
flash("Login successful.")
return redirect(f"/restaurant-dashboard/{restaurant.id}")
@app.route("/logout")
def logout():
"""Log out of a restaurant account."""
if session.get("restaurant_id"):
del session["restaurant_id"]
flash("Logout successful.")
return redirect("/")
@app.route("/register", methods=["GET"])
def show_registration_form():
"""Show registration form for restaurants."""
return render_template("restaurant-register.html")
@app.route("/register", methods=["POST"])
def process_restaurant_registration():
"""Process restaurant registration."""
name = request.form.get("name")
email = request.form.get("email")
password = request.form.get("password")
street_address = request.form.get("street-address")
city = request.form.get("city")
state = request.form.get("state")
zipcode = request.form.get("zipcode")
if Restaurant.query.filter_by(email=email).first():
flash("An account with this email already exists.")
return redirect("/register")
new_restaurant = Restaurant(name=name,
email=email,
street_address=street_address,
city=city,
state=state,
zipcode=zipcode)
new_restaurant.set_password(password)
db.session.add(new_restaurant)
db.session.commit()
restaurant_id = new_restaurant.id
# Log in new restaurant.
session["restaurant_id"] = restaurant_id
flash(f"Successfully registered {name}.")
return redirect(f"/restaurant-dashboard/{restaurant_id}")
@app.route("/restaurant-dashboard/<int:restaurant_id>")
def show_restaurant_dashboard(restaurant_id):
"""Show a restaurant's dashboard where they can view and edit offers."""
if not check_authorization(restaurant_id):
return render_template("unauthorized.html")
restaurant = Restaurant.query.get(restaurant_id)
offers = restaurant.offers
return render_template("restaurant-dashboard.html",
restaurant=restaurant,
offers=offers)
@app.route("/restaurant-dashboard/<int:restaurant_id>/add-offer", methods=["POST"])
def add_offer(restaurant_id):
"""Add a new offer."""
if not check_authorization(restaurant_id):
return render_template("unauthorized.html")
restaurant = Restaurant.query.get(restaurant_id)
item = request.form.get("item")
new_offer = Offer(restaurant_id=restaurant_id,
item=item)
db.session.add(new_offer)
db.session.commit()
return redirect(f"/restaurant-dashboard/{restaurant_id}")
@app.route("/restaurant/delete/offer", methods=["POST"])
def delete_offer():
"""Delete an offer."""
offer_id = request.form.get("offer")
print(offer_id)
offer = Offer.query.get(offer_id)
print(offer)
db.session.delete(offer)
db.session.commit()
return "Success"
def check_authorization(restaurant_id):
"""Check to see if the logged in restaurant is authorized to view page."""
# Get the current user's id.
user_id = session.get("restaurant_id")
# If correct restaurant is not logged in, return False.
if user_id != restaurant_id:
return False
return True
# Add jinja datetime filters to format datetime object in posts and comments.
def datetimeformat(value, format="%b %-d, %Y at %-I:%M %p"):
return value.strftime(format)
app.jinja_env.filters['datetime'] = datetimeformat
def dateformat(value, format="%m-%d-%Y"):
return value.strftime(format)
app.jinja_env.filters['date'] = dateformat
def htmldateformat(value, format="%Y-%m-%dT%H:%M"):
return value.strftime(format)
app.jinja_env.filters['htmldatetime'] = htmldateformat
if __name__ == "__main__":
app.debug = False
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
connect_to_db(app)
app.run(host="0.0.0.0")