Answer To: Final Project: Pizza delivery app Objectives • Create an application that covers each part of the...
Sandeep Kumar answered on Mar 21 2021
templates/index.html
{% extends "layout.html" %} {% block title %} Index {% endblock %} {% block
content %}
The pizza with the best byte
Cooked until it's cooked
ORDER HERE
{% endblock %}
templates/layout.html
Get your CS Pizza
Home
{% if not current_user.is_authenticated %}
Login
{% endif %} {% if current_user.is_authenticated %}
Order_here
Logout
Profile
{% endif %}
Home
{% if not current_user.is_authenticated %}
Login
{% endif %} {% if current_user.is_authenticated %}
Order_here
Logout
Profile
{% endif %}
{% block content %}{% endblock %}
templates/login.html
{% extends "layout.html" %} {% block title %} Login {% endblock %} {% block
content %}
{% with messages = get_flashed_messages() %} {% if messages %}
{{ messages[0] }}
{% endif %} {% endwith %}
Remember me
Login
Sign up
{% endblock %}
templates/order.html
{% extends "layout.html" %} {% block title %} Order some pizza {% endblock %} {%
block content %}
Pizza Cart
{{ itemName }}
{{ itemQuantity }}
{{ itemPrice }}
TOTAL
$0.00
Place Order
The BIG Veg
Peppers, mushrooms, broccoli, spinach, red onion, sweet potato!
$12.00
-
+
Add to cart
Caroline Special
Fish, prawns, mussels, lobster, crab, anchovies, a tomato
$14.00
-
+
Add to cart
Lonely Pepperonly
Just pepperoni all by itself
$13.00
-
+
Add to cart
Few mushies on dough
Bag of mush, all you need
$22.00
-
+
Add to cart
{% endblock %}
templates/profile.html
{% extends "layout.html" %} {% block title %} Profile {% endblock %} {% block
content %}
Hi {{ current_user.name }}!
Customer Number: {{ current_user.id }}
Total orders: {{ orders.count() }}
{% for order in orders %}
{{ order.datetime.date().strftime("%d/%m/%Y") }}
{% for pizza in order.orderData %}
{{ order.orderData[pizza]["quantity"] }} x
{{ pizza }}
${{ order.orderData[pizza]["price"] }}
{% endfor %}
Total:
${{ order.total }}
{% endfor %}
{% endblock %}
templates/signup.html
{% extends "layout.html" %} {% block title %} Signup {% endblock %} {% block
content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% if messages[0] == "Email address already exists" %}
{{ messages[0] }}. Go to Login page
{% endif %}
{% if messages[0] == "Please use a longer password" %}
{{ messages[0] }}.
(min 6 characters)
{% endif %}
{% endif %} {% endwith %}
Sign up
{% endblock %}
app.py
# import requests
import os
from flask import Flask, render_template, request, redirect, session, url_for, flash
from flask_login import LoginManager, login_user,logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
import json
# Config stuff
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql:///cspizza"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['SECRET_KEY'] = 'XF!1E18U&Ci!eLr*zfB7s&1$ZKtv^9D'
# app.config['TEMPLATES_AUTO_RELOAD'] = True
# app.jinja_env.auto_reload = True
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
# Link model with app
from models import Pizza, Order, User
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
remember = True if request.form.get("remember") else False
user = User.query.filter_by(email=email).first()
if not user or not check_password_hash(user.password, password):
flash("Please check your login details and try again")
return redirect(url_for("login")) # if user doesn't exist or password is wrong redirect to login
# If the user passes the check redirect to orders/ profile
login_user(user, remember=remember)
return redirect(url_for("order"))
return render_template("login.html")
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
email = request.form.get("email")
name = request.form.get("name")
password = request.form.get("password")
user = User.query.filter_by(email=email).first() #If this returns a user than email address already exists
if user:
flash("Email address already exists")
return redirect(url_for("signup"))
if len(password) < 6:
flash("Please use a longer password")
return redirect(url_for("signup"))
new_user = User(email=email, name=name, password=generate_password_hash(password, method="sha256"))
db.session.add(new_user)
db.session.commit()
return redirect(url_for("login"))
return render_template("signup.html")
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("index"))
@app.route("/order", methods=["GET", "POST"])
@login_required
def order():
errors = []
if request.method == "POST":
try:
pizzaNames = request.form.getlist("itemName")
pizzaQuantities = request.form.getlist("itemQuantity")
pizzaPrices = request.form.getlist("itemPrice")
totalPrice = request.form.getlist("totalPrice")
orderData = {}
for i, pizza in enumerate(pizzaNames):
orderData[pizza] = {
"quantity": pizzaQuantities[i],
"price": pizzaPrices[i]
}
order = Order(
user_id=current_user.id,
orderData=json.dumps(orderData),
total=float(totalPrice[0])
)
db.session.add(order)
db.session.commit()
except Exception as error:
# errors.append(
# "Unable to add Order to database"
# )
# print(errors)
db.session.flush()
db.session.rollback()
print(error)
return redirect("/order")
else:
return render_template("order.html")
@app.route("/profile", methods=["GET"])
@login_required
def profile():
past_orders = Order.query.filter_by(user_id=current_user.id)
for order in past_orders:
order.orderData = json.loads(order.orderData)
return render_template("profile.html", orders=past_orders)
if __name__ == "__main__":
app.run(debug=True)
hello_cli.txt
Hello command line
manage.py
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)
if __name__ == "__main__":
manager.run()
# python manage.py db migrate
# python manage.py db upgrade
models.py
from flask_login import UserMixin
from datetime import datetime, timezone
from app import db
from sqlalchemy.dialects.postgresql import JSON
class Pizza(db.Model):
__tablename__ = "pizzas"
# Will run the first time we create a new pizza
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
toppings = db.Column(db.String())
price = db.Column(db.Float)
# Will represent the object when we query for it
def __init__(self, name, toppings):
self.name = name
self.toppings = toppings
self.price = price
def __repr__(self):
return f""
class Order(db.Model):
__tablename__ = "orders"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
orderData = db.Column(JSON)
total = db.Column(db.Float)
datetime = db.Column(db.DateTime, nullable=False, default=datetime.now(timezone.utc))
def __init__(self, user_id, orderData, total):
self.user_id = user_id
self.orderData = orderData
self.total = total
def __repr__(self):
return f"Order no: {self.id} - Total price: {self.total} - data: {self.orderData}"
class User(UserMixin, db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, nullable=False)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
orders = db.relationship("Order", backref="users", lazy=True)
def __init__(self, email, password, name):
self.email = email
self.password = password
self.name = name
# self.orders = orders
def __repr__(self):
return f"User email: {self.email}"
Procfile
web: gunicorn app:app
requirements.txt
alembic==1.4.2
astroid==2.4.1
click==7.1.2
colorama==0.4.3
Flask==1.1.2
Flask-Login==0.5.0
Flask-Migrate==2.5.3
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.1
gunicorn==20.0.4
isort==4.3.21
itsdangerous==1.1.0
Jinja2==2.11.2
lazy-object-proxy==1.4.3
Mako==1.1.2
MarkupSafe==1.1.1
mccabe==0.6.1
psycopg2==2.8.5
pylint==2.5.2
python-dateutil==2.8.1
python-editor==1.0.4
six==1.14.0
SQLAlchemy==1.3.17
toml==0.10.1
Werkzeug==1.0.1
wrapt==1.12.1
runtime.txt
python-3.8.1
start.bat
@ECHO OFF
set APP_SETTINGS="config.DevelopmentConfig"
workon cspizza
.vscode/launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
...