0

I'm working on my final project and when clicking on the link generated by the flask run command, I receive the following error: "builtins.NameError NameError: name 'usd' is not defined".

I don't know what the problem is (the beginning of my code it's very similar to the one of pset7/finance).

Would someone have an idea?

Following the code from my "application.py" file

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import mkdtemp

from helpers import *
from datetime import date

import time
import math

# configure application
app = Flask(__name__)

# ensure responses aren't cached
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response

# custom filter
app.jinja_env.filters["usd"] = usd

# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# configure CS50 Library to use SQLite database
db = SQL("sqlite:///project.db")

@app.route("/")
@login_required
def kitchen_cupboards():

    """Show what's in the users' kitchen_cupboards"""

    # query database to get the goods' that are in the connected users' kitchen cupboards
    cupboards = db.execute("SELECT goods_name, quantity, total_price, expiry_date FROM \
    goods WHERE id = :id", id=session["user_id"])

    # initialization of the variable to get the total amount of money present in the kitchen_cupboards
    total_money_kitchen_cupboards = 0

    for cupboard in cupboards:
        # use of usd function for those values
        total_money_kitchen_cupboards = total_money_kitchen_cupboards + cupboard["total_price"]
        cupboard["total_price"] = usd(cupboard["total_price"])

        # determining days left to eat goods before expiry date
        year = int(cupboard["expiry_date"][0:4])
        month = int(cupboard["expiry_date"][5:7])
        day = int(cupboard["expiry_date"][8:10])
        expiry_date_rebuild = date(year, month, day)
        days_left = expiry_date_rebuild - date.today()
        # addition of current price and global amount of the share (price*quantity) on indexs
        cupboard['days_left'] = days_left.days

    # use kitchen_cupboards.html to present values (Jinja use in this file)
    return render_template("kitchen_cupboards.html", cupboards=cupboards,\
    total_money_kitchen_cupboards=usd(total_money_kitchen_cupboards))

@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in."""

    # forget any user_id
    session.clear()

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return apology("You must provide a username")

        # ensure password was submitted
        elif not request.form.get("password"):
            return apology("You must provide a password")

        # query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        # ensure username exists and password is correct
        if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
            return apology("invalid username and/or password")

        # remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # redirect user to the kitchen_cupboards home page
        return redirect(url_for("kitchen_cupboards"))

    # else if user reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out."""

    # forget any user_id
    session.clear()

    # redirect user to login form
    return redirect(url_for("login"))


@app.route("/register", methods=["GET", "POST"])
def register():

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username field isn't blank
        if not request.form.get("username"):
            return apology("You must provide a username")

        # ensure password & password confirmation fields aren't blank
        elif not request.form.get("password") or not request.form.get("password_confirmation"):
            return apology("You must provide a password and the confirmation of it")

        # ensure that password & password confirmation are the same
        elif (request.form.get("password")!=request.form.get("password_confirmation")):
            return apology("Password & password confirmation must be the same!")

        # hash the password
        hash=pwd_context.hash(request.form.get("password"))

        # check if username exists
        db_username = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        if not db_username:
            # add user to the database
            result=db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)

            # log the user automatically after he registered
            session["user_id"]=result
            return redirect(url_for("kitchen_cupboards"))

        else:
            return apology("The username already exists, pick another one please")

    else:
        return render_template("register.html")

@app.route("/add_goods", methods=["GET", "POST"])
@login_required
def add_goods():
    """Add goods to the kitchen_cupboards"""

    if request.method == "POST":
        goods_name = request.form.get("goods_name")
        quantity = int(request.form.get("quantity"))
        unit_price = float(request.form.get("price"))
        expiry_date = request.form.get("expiry_date")

        if not goods_name:
            return apology("You must provide a goods name in order to had it in your kitchen_cupboards")

        elif quantity <= 0:
            return apology("The quantity must be a positive integer")

        elif unit_price <= 0:
            return apology("The unit price must be a positive integer")

        if not expiry_date:
            return apology("You must specify the goods' expiry date in order to had it in your kitchen_cupboards")

        else:

            total_price = quantity * unit_price

            # query goods table to check if the goods is already in the kitchen_cupboards
            goods_query=db.execute("SELECT * FROM goods WHERE id=:id AND goods_name=:goods_name",\
            id=session["user_id"], goods_name=goods_name)

            if not goods_query:

                # query barcode table to check if the goods exists to get the JSON
                barcode=db.execute("SELECT * FROM barcode WHERE goods_name=:goods_name", goods_name=goods_name)
                print(barcode)

                #AJOUTER UN CHECK SI LE GOOD N'EST PAS PRESENT DANS LA BDD

                # add the goods to the 'goods' table
                goods=db.execute("INSERT INTO goods (id, goods_name, quantity, total_price, expiry_date)\
                VALUES(:id, :goods_name, :quantity, :total_price, :expiry_date)", \
                id=session["user_id"], goods_name=goods_name, quantity=quantity, total_price=total_price,\
                expiry_date=expiry_date)

            else:
                # update 'goods' table
                goods_update=db.execute("UPDATE goods SET quantity=quantity+:quantity, total_price=total_price+:total_price,\
                expiry_date=:expiry_date WHERE id=:id AND goods_name=:goods_name", \
                quantity=quantity, total_price=total_price, expiry_date=expiry_date,\
                id=session["user_id"], goods_name=goods_name)

                # query barcode table to check if the goods exists to get the JSON
                query_barcode=db.execute("SELECT * FROM barcode WHERE goods_name=:goods_name", goods_name=goods_name)

                # use of the barcode function defined in helpers.py to get the JSON associated to the goods
                goods_barcode=lookup(query_barcode[0]["barcode"])

                return jsonify(goods_barcode)

        return render_template("add_goods.html")

    else:
        return render_template("add_goods.html")


@app.route("/chart")
def chart():
    """Defining chart to see the evolution of waste for 2017"""

    money_loss = {}
    money_loss["January"] = 0
    money_loss["February"] = 0
    money_loss["March"] = 0
    money_loss["April"] = 0
    money_loss["May"] = 0
    money_loss["June"] = 0
    money_loss["July"] = 0
    money_loss["August"] = 0
    money_loss["September"] = 0
    money_loss["October"] = 0
    money_loss["November"] = 0
    money_loss["December"] = 0

    money_loss["Total_Money_Loss_February"] = 0
    money_loss["Total_Money_Loss_March"] = 0
    money_loss["Total_Money_Loss_April"] = 0
    money_loss["Total_Money_Loss_May"] = 0
    money_loss["Total_Money_Loss_June"] = 0
    money_loss["Total_Money_Loss_July"] = 0
    money_loss["Total_Money_Loss_August"] = 0
    money_loss["Total_Money_Loss_September"] = 0
    money_loss["Total_Money_Loss_October"] = 0
    money_loss["Total_Money_Loss_November"] = 0
    money_loss["Total_Money_Loss_December"] = 0

    # query 'threw' table to get threw date and associated total price
    threws = db.execute("SELECT threw_date, total_price FROM threw WHERE id = :id", id=session["user_id"])

    for threw in threws:

        year = int(threw["threw_date"][0:4])

        # check that the waste was done in 2017
        if year == 2017:
            # determining month of waste for evolution over time graphs
            month = int(threw["threw_date"][5:7])

            if month == 1:
                money_loss["January"] = money_loss["January"] + threw["total_price"]

            elif month == 2:
                money_loss["February"] = money_loss["February"] + threw["total_price"]

            elif month == 3:
                money_loss["March"] = money_loss["March"] + threw["total_price"]

            elif month == 4:
                money_loss["April"] = money_loss["April"] + threw["total_price"]

            elif month == 5:
                money_loss["May"] = money_loss["May"] + threw["total_price"]

            elif month == 6:
                money_loss["June"] = money_loss["June"] + threw["total_price"]

            elif month == 7:
                money_loss["July"] = money_loss["July"] + threw["total_price"]

            elif month == 8:
                money_loss["August"] = money_loss["August"] + threw["total_price"]

            elif month == 9:
                money_loss["September"] = money_loss["September"] + threw["total_price"]

            elif month == 10:
                money_loss["October"] = money_loss["October"] + threw["total_price"]

            elif month == 11:
                money_loss["November"] = money_loss["November"] + threw["total_price"]

            else:
                money_loss["December"] = money_loss["December"] + threw["total_price"]

        money_loss["Total_Money_Loss_February"] = money_loss["January"] + money_loss["February"]
        money_loss["Total_Money_Loss_March"] = money_loss["Total_Money_Loss_February"] + money_loss["March"]
        money_loss["Total_Money_Loss_April"] = money_loss["Total_Money_Loss_March"] + money_loss["April"]
        money_loss["Total_Money_Loss_May"] = money_loss["Total_Money_Loss_April"] + money_loss["May"]
        money_loss["Total_Money_Loss_June"] = money_loss["Total_Money_Loss_May"] + money_loss["June"]
        money_loss["Total_Money_Loss_July"] = money_loss["Total_Money_Loss_June"] + money_loss["July"]
        money_loss["Total_Money_Loss_August"] = money_loss["Total_Money_Loss_July"] + money_loss["August"]
        money_loss["Total_Money_Loss_September"] = money_loss["Total_Money_Loss_August"] + money_loss["September"]
        money_loss["Total_Money_Loss_October"] = money_loss["Total_Money_Loss_September"] + money_loss["October"]
        money_loss["Total_Money_Loss_November"] = money_loss["Total_Money_Loss_October"] + money_loss["November"]
        money_loss["Total_Money_Loss_December"] = money_loss["Total_Money_Loss_November"] + money_loss["December"]

    labels = ["January","February","March","April","May","June","July","August","September","October","November","December"]

    values = [money_loss["January"],money_loss["February"],money_loss["March"],money_loss["April"],money_loss["May"],\
    money_loss["June"],money_loss["July"],money_loss["August"],money_loss["September"],money_loss["October"],\
    money_loss["November"], money_loss["December"]]

    max_values = (math.ceil(max(values))) + 1
    steps = math.ceil(max_values/2)

    values_2 = [money_loss["January"],money_loss["Total_Money_Loss_February"],money_loss["Total_Money_Loss_March"],money_loss["Total_Money_Loss_April"],money_loss["Total_Money_Loss_May"], money_loss["Total_Money_Loss_June"],money_loss["Total_Money_Loss_July"],money_loss["Total_Money_Loss_August"],money_loss["Total_Money_Loss_September"],money_loss["Total_Money_Loss_October"], money_loss["Total_Money_Loss_November"], money_loss["Total_Money_Loss_December"]]

    max_values_2 = (math.ceil(max(values_2))) + 1
    steps_2 = math.ceil(max_values_2/2)

    return render_template('chart.html', values=values, labels=labels, values_2=values_2, steps_2=steps_2, max_values_2=max_values_2, steps=steps, max_values=max_values)

@app.route("/ate_goods", methods=["GET", "POST"])
@login_required
def ate_goods():
    """Ate goods to be removed from the kitchen_cupboards"""

    if request.method == "POST":
        goods_name = request.form.get("goods_name")
        quantity = int(request.form.get("quantity"))

        if not goods_name:
            return apology("You must provide a goods name in order to had it in your kitchen_cupboards")

        elif quantity <= 0:
            return apology("The quantity must be a positive integer")

        else:

            # query database to get total value associated to a good
            query_goods = db.execute("SELECT goods_name, quantity, total_price FROM \
            goods WHERE id = :id AND goods_name = :goods_name", id=session["user_id"], goods_name=goods_name)

            if not query_goods:
                return apology("The goods' name you entered is not present in the kitchen cupboards")

            elif query_goods[0]['quantity'] < quantity:
                return apology("You don't have the quantity that you want to withdraw in your kitchen cupboards")

            else:
                average_value = query_goods[0]['total_price'] / query_goods[0]['quantity']
                total_value_withdraw = quantity * average_value

                # update 'goods' table
                goods=db.execute("UPDATE goods SET quantity=quantity-:quantity, total_price=total_price-:total_value_withdraw\
                WHERE id=:id AND goods_name=:goods_name", \
                quantity=quantity, total_value_withdraw=total_value_withdraw, id=session["user_id"], goods_name=goods_name)

        return render_template("ate_goods.html")

    else:
        return render_template("ate_goods.html")


@app.route("/threw_goods", methods=["GET", "POST"])
@login_required
def threw_goods():
    """Threw goods to be removed from the kitchen_cupboards"""

    if request.method == "POST":
        goods_name = request.form.get("goods_name")
        quantity = int(request.form.get("quantity"))

        if not goods_name:
            return apology("You must provide a goods name in order to had it in your kitchen_cupboards")

        elif quantity <= 0:
            return apology("The quantity must be a positive integer")

        else:

            # query database to get total value associated to a good
            query_goods = db.execute("SELECT goods_name, quantity, total_price FROM \
            goods WHERE id = :id AND goods_name = :goods_name", id=session["user_id"], goods_name=goods_name)

            if not query_goods:
                return apology("The goods' name you entered is not present in the kitchen cupboards")

            elif query_goods[0]['quantity'] < quantity:
                return apology("You don't have the quantity that you want to withdraw in your kitchen cupboards")

            else:
                average_value = query_goods[0]['total_price'] / query_goods[0]['quantity']
                total_value_withdraw = quantity * average_value

                threw_date = date.today()

                # update 'goods' table
                goods=db.execute("UPDATE goods SET quantity=quantity-:quantity, total_price=total_price-:total_value_withdraw\
                WHERE id=:id AND goods_name=:goods_name", \
                quantity=quantity, total_value_withdraw=total_value_withdraw, id=session["user_id"], goods_name=goods_name)

                # insert into the 'threw' table
                threw=db.execute("INSERT INTO threw (id, goods_name, quantity, total_price, threw_date)\
                VALUES(:id, :goods_name, :quantity, :total_value_withdraw, :threw_date)", \
                id=session["user_id"], goods_name=goods_name, quantity=quantity, total_value_withdraw=total_value_withdraw,\
                threw_date=threw_date)

        return render_template("threw_goods.html")

    else:
        return render_template("threw_goods.html")
1
  • Forgot the : "Hi everyone" :)
    – WLC
    Dec 18 '17 at 16:08
1

In pset7, the usd function is included in helpers.py and then you import helpers. If you want to use it here, you could simply include the function in your code:

def usd(value):
"""Formats value as USD."""
return f"${value:,.2f}"
1
  • Hello curiouskiwi, Thanks for your help I missed that in my code!
    – WLC
    Dec 19 '17 at 7:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .