Skip to content

Commit

Permalink
Merge pull request Azure-Samples#21 from pamelafox/pamela-style
Browse files Browse the repository at this point in the history
Style improvements to Flask sample
  • Loading branch information
vmagelo authored Feb 8, 2023
2 parents 346b123 + 9783e20 commit d4d87ba
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 22 deletions.
36 changes: 18 additions & 18 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
from datetime import datetime
import os
from datetime import datetime

from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, redirect, render_template, request, send_from_directory, url_for
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect


app = Flask(__name__, static_folder='static')
csrf = CSRFProtect(app)

# 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')
if 'WEBSITE_HOSTNAME' not 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')
# production
print("Loading config.production.")
app.config.from_object('azureproject.production')

app.config.update(
SQLALCHEMY_DATABASE_URI=app.config.get('DATABASE_URI'),
Expand All @@ -37,13 +37,13 @@
@app.route('/', methods=['GET'])
def index():
print('Request for index page received')
restaurants = Restaurant.query.all()
restaurants = Restaurant.query.all()
return render_template('index.html', restaurants=restaurants)

@app.route('/<int:id>', methods=['GET'])
def details(id):
restaurant = Restaurant.query.where(Restaurant.id == id).first()
reviews = Review.query.where(Review.restaurant==id)
reviews = Review.query.where(Review.restaurant == id)
return render_template('details.html', restaurant=restaurant, reviews=reviews)

@app.route('/create', methods=['GET'])
Expand Down Expand Up @@ -94,21 +94,21 @@ def add_review(id):
review.review_text = review_text
db.session.add(review)
db.session.commit()
return redirect(url_for('details', id=id))

return redirect(url_for('details', id=id))

@app.context_processor
def utility_processor():
def star_rating(id):
reviews = Review.query.where(Review.restaurant==id)
reviews = Review.query.where(Review.restaurant == id)

ratings = []
review_count = 0;
review_count = 0
for review in reviews:
ratings += [review.rating]
review_count += 1

avg_rating = sum(ratings)/len(ratings) if ratings else 0
avg_rating = sum(ratings) / len(ratings) 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}

Expand All @@ -120,4 +120,4 @@ def favicon():
'favicon.ico', mimetype='image/vnd.microsoft.icon')

if __name__ == '__main__':
app.run()
app.run()
2 changes: 1 addition & 1 deletion azureproject/development.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand Down
2 changes: 1 addition & 1 deletion azureproject/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
SECRET_KEY = os.getenv('SECRET_KEY', 'flask-insecure-7ppocbnx@w71dcuinn*t^_mzal(t@o01v3fee27g%rg18fc5d@')

ALLOWED_HOSTS = [os.environ['WEBSITE_HOSTNAME']] if 'WEBSITE_HOSTNAME' in os.environ else []
CSRF_TRUSTED_ORIGINS = ['https://'+ os.environ['WEBSITE_HOSTNAME']] if 'WEBSITE_HOSTNAME' in os.environ else []
CSRF_TRUSTED_ORIGINS = ['https://' + os.environ['WEBSITE_HOSTNAME']] if 'WEBSITE_HOSTNAME' in os.environ else []

# Configure Postgres database; the full username for PostgreSQL flexible server is
# username (not @sever-name).
Expand Down
5 changes: 3 additions & 2 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import validates

from app import db
Expand All @@ -10,6 +10,7 @@ class Restaurant(db.Model):
name = Column(String(50))
street_address = Column(String(50))
description = Column(String(250))

def __str__(self):
return self.name

Expand All @@ -28,4 +29,4 @@ def validate_rating(self, key, value):
return value

def __str__(self):
return self.restaurant.name + " (" + self.review_date.strftime("%x") +")"
return f"{self.restaurant.name} ({self.review.date:%x})"

0 comments on commit d4d87ba

Please sign in to comment.