-
Notifications
You must be signed in to change notification settings - Fork 15
/
app.py
188 lines (153 loc) · 6.59 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
import os
import uuid
from datetime import datetime
from urllib.parse import urlparse
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_wtf.csrf import CSRFProtect
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
from azureproject.get_conn import get_conn
from requests import RequestException
app = Flask(__name__, static_folder='static')
csrf = CSRFProtect(app)
STORAGE_CONTAINER_NAME = 'photos'
# WEBSITE_HOSTNAME exists only in production environment
if not 'WEBSITE_HOSTNAME' in os.environ:
# local development, where we'll use environment variables
print("Loading config.development and environment variables from .env file.")
app.config.from_object('azureproject.development')
else:
# production
print("Loading config.production.")
app.config.from_object('azureproject.production')
with app.app_context():
app.config.update(
SQLALCHEMY_TRACK_MODIFICATIONS=False,
SQLALCHEMY_DATABASE_URI=get_conn(),
)
# Initialize the database connection
db = SQLAlchemy(app)
# Enable Flask-Migrate commands "flask db init/migrate/upgrade" to work
migrate = Migrate(app, db)
# The import must be done after db initialization due to circular import issue
from models import Restaurant, Review
@app.route('/', methods=['GET'])
def index():
print('Request for index page received')
restaurants = Restaurant.query.all()
return render_template('index.html', restaurants=restaurants)
@app.route('/<int:id>', methods=['GET'])
def details(id):
return details(id,'')
def details(id, message):
restaurant = Restaurant.query.where(Restaurant.id == id).first()
reviews = Review.query.where(Review.restaurant==id)
image_path = get_account_url() + "/" + STORAGE_CONTAINER_NAME
return render_template('details.html', restaurant=restaurant, reviews=reviews, message=message, image_path=image_path)
@app.route('/create', methods=['GET'])
def create_restaurant():
print('Request for add restaurant page received')
return render_template('create_restaurant.html')
@app.route('/add', methods=['POST'])
@csrf.exempt
def add_restaurant():
try:
name = request.values.get('restaurant_name')
street_address = request.values.get('street_address')
description = request.values.get('description')
if (name == "" or description == "" ):
raise RequestException()
except (KeyError, RequestException):
# Redisplay the restaurant entry form.
return render_template('create_restaurant.html',
message='Restaurant not added. Include at least a restaurant name and description.')
else:
restaurant = Restaurant()
restaurant.name = name
restaurant.street_address = street_address
restaurant.description = description
db.session.add(restaurant)
db.session.commit()
return redirect(url_for('details', id=restaurant.id))
@app.route('/review/<int:id>', methods=['POST'])
@csrf.exempt
def add_review(id):
try:
user_name = request.values.get('user_name')
rating = request.values.get('rating')
review_text = request.values.get('review_text')
if (user_name == "" or rating == None):
raise RequestException()
except (KeyError, RequestException):
# Redisplay the review form.
restaurant = Restaurant.query.where(Restaurant.id == id).first()
reviews = Review.query.where(Review.restaurant==id)
return details(id, 'Review not added. Include at least a name and rating for review.')
else:
if request.files['reviewImage']:
image_data = request.files['reviewImage']
# Get size.
size = len(image_data.read())
image_data.seek(0)
print("Original image name = " + image_data.filename)
print("File size = " + str(size))
if (size > 2048000):
return details(id, 'Image too big, try again.')
# Get account_url based on environment
print("account_url = " + get_account_url())
# Create client
azure_credential = DefaultAzureCredential()
blob_service_client = BlobServiceClient(
account_url = get_account_url(),
credential=azure_credential)
# Get file name to use in database
image_name = str(uuid.uuid4()) + ".png"
# Create blob client
blob_client = blob_service_client.get_blob_client(container=STORAGE_CONTAINER_NAME, blob=image_name)
print("\nUploading to Azure Storage as blob:\n\t" + image_name)
# Upload file
blob_client.upload_blob(image_data)
else:
# No image for review
image_name=None
review = Review()
review.restaurant = id
review.review_date = datetime.now()
review.user_name = user_name
review.rating = int(rating)
review.review_text = review_text
review.image_name = image_name
db.session.add(review)
db.session.commit()
return redirect(url_for('details', id=id))
@app.context_processor
def utility_processor():
def star_rating(id):
reviews = Review.query.where(Review.restaurant==id)
ratings = []
review_count = 0;
for review in reviews:
ratings += [review.rating]
review_count += 1
avg_rating = round(sum(ratings)/len(ratings), 2) if ratings else 0
stars_percent = round((avg_rating / 5.0) * 100) if review_count > 0 else 0
return {'avg_rating': avg_rating, 'review_count': review_count, 'stars_percent': stars_percent}
return dict(star_rating=star_rating)
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
def get_account_url():
if not 'AZURE_STORAGEBLOB_RESOURCEENDPOINT' in os.environ:
# Create LOCAL_USE_AZURE_STORAGE environment variable to use Azure Storage locally.
if 'WEBSITE_HOSTNAME' in os.environ or ("LOCAL_USE_AZURE_STORAGE" in os.environ):
print("Using Azure Storage.")
return "https://%s.blob.core.windows.net" % os.environ['STORAGE_ACCOUNT_NAME']
else:
return os.environ['STORAGE_ACCOUNT_NAME']
else:
return os.environ['AZURE_STORAGEBLOB_RESOURCEENDPOINT'].rstrip('/')
if __name__ == '__main__':
app.run()