11import os
22from datetime import datetime
3- from flask import Flask , redirect , render_template , request , send_from_directory , url_for , jsonify
3+
4+ from flask import Flask , redirect , render_template , request , send_from_directory , url_for
45from flask_migrate import Migrate
56from flask_sqlalchemy import SQLAlchemy
67from flask_wtf .csrf import CSRFProtect
78
8- # Main application
9+
910app = Flask (__name__ , static_folder = 'static' )
1011csrf = CSRFProtect (app )
1112
12- # Configuración según entorno
13+ # WEBSITE_HOSTNAME exists only in production environment
1314if 'WEBSITE_HOSTNAME' not in os .environ :
15+ # local development, where we'll use environment variables
1416 print ("Loading config.development and environment variables from .env file." )
1517 app .config .from_object ('azureproject.development' )
16- else :
18+ else :
19+ # production
1720 print ("Loading config.production." )
1821 app .config .from_object ('azureproject.production' )
1922
2225 SQLALCHEMY_TRACK_MODIFICATIONS = False ,
2326)
2427
25- # Inicializar base de datos
28+ # Initialize the database connection
2629db = SQLAlchemy (app )
30+
31+ # Enable Flask-Migrate commands "flask db init/migrate/upgrade" to work
2732migrate = Migrate (app , db )
2833
29- # Importar modelos después de inicializar db
34+ # The import must be done after db initialization due to circular import issue
3035from models import Restaurant , Review , ImageData
3136
37+ #@app.route('/', methods=['GET'])
38+ #def index():
39+ # print('Request for index page received')
40+ # restaurants = Restaurant.query.all()
41+ # return render_template('index.html', restaurants=restaurants)
42+
3243@app .route ('/' , methods = ['GET' ])
3344def index ():
3445 print ('Request for index page received' )
35- restaurants = Restaurant .query .all ()
36- return render_template ('index.html' , restaurants = restaurants )
46+ images = ImageData .query .all ()
47+ return render_template ('index.html' , images = images )
3748
3849@app .route ('/<int:id>' , methods = ['GET' ])
3950def details (id ):
@@ -54,6 +65,7 @@ def add_restaurant():
5465 street_address = request .values .get ('street_address' )
5566 description = request .values .get ('description' )
5667 except (KeyError ):
68+ # Redisplay the question voting form.
5769 return render_template ('add_restaurant.html' , {
5870 'error_message' : "You must include a restaurant name, address, and description" ,
5971 })
@@ -64,6 +76,7 @@ def add_restaurant():
6476 restaurant .description = description
6577 db .session .add (restaurant )
6678 db .session .commit ()
79+
6780 return redirect (url_for ('details' , id = restaurant .id ))
6881
6982@app .route ('/review/<int:id>' , methods = ['POST' ])
@@ -74,6 +87,7 @@ def add_review(id):
7487 rating = request .values .get ('rating' )
7588 review_text = request .values .get ('review_text' )
7689 except (KeyError ):
90+ #Redisplay the question voting form.
7791 return render_template ('add_review.html' , {
7892 'error_message' : "Error adding review" ,
7993 })
@@ -93,38 +107,61 @@ def add_review(id):
93107def utility_processor ():
94108 def star_rating (id ):
95109 reviews = Review .query .where (Review .restaurant == id )
110+
96111 ratings = []
97112 review_count = 0
98113 for review in reviews :
99- ratings . append ( review .rating )
114+ ratings += [ review .rating ]
100115 review_count += 1
116+
101117 avg_rating = sum (ratings ) / len (ratings ) if ratings else 0
102118 stars_percent = round ((avg_rating / 5.0 ) * 100 ) if review_count > 0 else 0
103119 return {'avg_rating' : avg_rating , 'review_count' : review_count , 'stars_percent' : stars_percent }
120+
104121 return dict (star_rating = star_rating )
105122
106123@app .route ('/images' , methods = ['GET' ])
107124def image_table ():
108125 print ('Request for image table page received' )
109126 images = ImageData .query .order_by (ImageData .upload_time .desc ()).all ()
110- return render_template ('image_table .html' , images = images )
127+ return render_template ('index .html' , images = images )
111128
112- @app .route ('/api/images' , methods = ['GET' ])
113- def image_json ():
114- images = ImageData .query .order_by (ImageData .upload_time .desc ()).all ()
115- data = [
116- {
117- "id" : img .id ,
118- "filename" : img .filename ,
119- "username" : img .username ,
120- "upload_time" : img .upload_time .isoformat (),
121- "pixel_rojo" : img .pixel_rojo ,
122- "pixel_verde" : img .pixel_verde ,
123- "pixel_azul" : img .pixel_azul
124- }
125- for img in images
126- ]
127- return jsonify (data )
129+ @csrf .exempt
130+ @app .route ('/upload_image' , methods = ['POST' ])
131+ def upload_image ():
132+ print ('Request to upload image received' )
133+ if not request .is_json :
134+ return jsonify ({"error" : "Request must be JSON" }), 400
135+
136+ data = request .get_json ()
137+ filename = data .get ('filename' )
138+ pixel_red = data .get ('pixel_red' )
139+ pixel_green = data .get ('pixel_green' )
140+ pixel_blue = data .get ('pixel_blue' )
141+ username = data .get ('username' )
142+
143+
144+ if not all ([filename , pixel_red , pixel_green , pixel_blue , username ]):
145+ return jsonify ({"error" : "All fields ('filename', 'pixel_red', 'pixel_green', 'pixel_blue', 'username') are required" }), 400
146+
147+ try :
148+ new_image = ImageData (
149+ filename = filename ,
150+ pixel_red = pixel_red ,
151+ pixel_green = pixel_green ,
152+ pixel_blue = pixel_blue ,
153+ username = username ,
154+ upload_time = datetime .now (timezone .utc )
155+
156+ )
157+ #db.session.create_all()
158+ #db.session.commit()
159+ db .session .add (new_image )
160+ db .session .commit ()
161+ return jsonify ({"message" : "Image uploaded successfully" }), 201
162+ except Exception as e :
163+ db .session .rollback ()
164+ return jsonify ({"error" : str (e )}), 500
128165
129166@app .route ('/favicon.ico' )
130167def favicon ():
0 commit comments