1

The error I get

I'm trying to finish up pset7 and was trying to launch the web server to view the result but every time that I do I get the above error. I'm not really sure what I'm doing wrong. I ran flask in the /finance folder where application.py is located but I still get this result. I tried restarting the cs50 IDE and reinstalling the pip3 but that didn't seem to work. I don't have any errors in my application.py that I'm aware of. I'll post my application.py just in case there are issues in there that are contributing to this problem. Thanks in advance!

Application.py:

from cs50 import SQL
from flask import Flask, flash, 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 gettempdir


from helpers import *
from register.html import *
from quote.html import *
from quoted.html import *
from buy.html import *

# 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"] = gettempdir()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

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

@app.route("/")
@login_required
def index():
stocks = db.execute("SELECT stock, shares AS quantities FROM portfolio WHERE id = :id GROUP BY stock, symbol ORDER BY stock",id = session["user_id"])
shares = db.execute("SELECT shares AS quantities FROM portfolio WHERE id = :id", id = session["user_id"])

currentprices = []

# get current price for each group with lookup function
for stock in stocks:
    symbol = str(stock["symbol"])
    quote = lookup(symbol)
    currentprices.append(quote['price'])

cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
grand_total = cash + (quote * shares)

# render the template with the results 
return render_template("index.html", stocks = stocks, cash = cash, currentprices = currentprices, grand_total = grand_total)


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock."""
if request.method == "POST":
    shares = int(request.get.form("shares"))

    """Make sure user inputs symbol"""
    if not request.form.get("symbol"):
        return apology("Please input symbol")

    """Check Yahoo finance for quote"""
    stock = lookup(request.form.get("symbol"))
    if not stock:
        return apology("Could not find stock")

    """Ensure user inputs valid number"""
    if not shares >= 0:
        return apology("Please input a valid number")

    stock = lookup(request.form.get("symbol"))
    name = stock['name']
    symbol = stock['symbol']
    price = stock['price']


    """See if user can buy stock"""
    balance = db.execute("SELECT cash FROM users WHERE id =1")
    cost = shares * price
    if not balance >= cost:
        return apology("Insufficient cash to make purchase")
    else:
        purchase = db.execute("INSERT INTO portfolio (shares, stock, price) VALUES (shares, symbol, balance)")
        db.execute("UPDATE users SET cash = cash - cost WHERE id = 1")
        transaction = "buy"
        update_history = db.execute("INSERT INTO history (transaction, date, symbol, shares, price, time) VALUES (transaction, CURDATE(), stock, shares, price, CURTIME())")

else:
    return render_template("buy.html")    

@app.route("/history")
@login_required
def history():
"""Show history of transactions."""
stocks = db.execute("SELECT transaction, date, symbol, shares, price, time FROM history WHERE id = :id GROUP BY transaction, date, symbol, shares, price, time ORDER BY stock", id = session["user_id"])

return render_template("history.html", stocks = stocks)

@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("must provide username")

    # ensure password was submitted
    elif not request.form.get("password"):
        return apology("must provide 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 home page
    return redirect(url_for("index"))

# 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("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method == "POST":

    """Make sure user inputs symbol"""
    if not request.form.get("symbol"):
        return apology("Please input symbol")

    """Check Yahoo finance for quote"""
    stock = lookup(request.form.get("symbol"))
    if not stock:
        return apology("Could not find stock")

    return render_template("quoted.html", stock=stock)

elif request.method == "GET":
    return render_template("quote.html")

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

"""Forget any user id"""
session.clear()

"""Register user"""
if request.method == "POST":

    """Ensure username was submitted"""
    if not request.form.get("username"):
        return apology("Need to provide username")

    """Ensure password was submitted"""
    if not request.form.get("password"):
        return apology("Need to provide password")

    """Ensure same password was entered twice"""
    if request.form.get("password") != request.form.get("password confirmation"):
        return apology("Passwords do not match")

    """hash password"""
    hash = pwd_context.encrypt(request.form.get("password"))

    """log user to database or return apology if username already exists"""
    result = db.execute("INSERT INTO users(username, hash) VALUES(:username, :hash)", username= request.form.get("username"), hash=hash)
    if not result:
        return apology("Sorry this username already exists")

    """if register successful, log user in automatically and store session id"""
    rows = db.execute("SELECT * FROM users WHERE username = :username", username= request.form.get("username"))
    if not rows:
        return apology("Sorry, something went wrong")

    session["user_id"] = rows[0]["id"]

    return render_template("register.html")

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock."""
if request.method == "POST":
    shares = int(request.get.form("shares"))

    """Make sure user inputs symbol"""
    if not request.form.get("symbol"):
        return apology("Please input symbol")

    """Check Yahoo finance for quote"""
    stock = lookup(request.form.get("symbol"))
    if not stock:
        return apology("Could not find stock")

    """Ensure user inputs valid number"""
    if not shares >= 0:
        return apology("Please input a valid number")

    stock = lookup(request.form.get("symbol"))
    name = stock['name']
    symbol = stock['symbol']
    price = stock['price']


    """See if user actually has the number of shares that they want to sell"""
    current_shares = db.execute("SELECT shares FROM portfolio WHERE id =1")
    potential_selling_shares = shares
    if not current_shares >= potential_selling_shares:
        return apology("Sorry you are trying to sell more shares than you have")
    else:
        profit = price * shares
        transaction = "sell"
        sell = db.execute("INSERT INTO users (cash) VALUES (profit)")
        remove = db.execute("DELETE FROM portfolio (shares, stock, price) VALUES (shares, stock, price")
        update_history = db.execute("INSERT INTO history (transaction, date, symbol, shares, price, time) VALUES (transaction, CURDATE(), stock, shares, price, CURTIME())")

else:
    return render_template("sell.html")

@app.route("/update_cash", methods=["GET", "POST"])
def update_cash():
"""Update balance in cash"""
if request.method == "POST":
    added_money = int(request.get.form("update_cash"))

    """Ensure user inputs valid number"""
    if not added_money >= 0:
        return apology("Please input a valid number")

    """Add to current cash balance"""
    update_balance = db.execute("INSERT INTO users (cash) VALUES (added_money)")

else:
    return render_template("update_cash.html")
8
  • Were you able to solve the problem? – Ianardo Mar 23 '17 at 2:44
  • 1
    No unfortunately, I ended up just submitting what I had. I had already spent like 16 hours on that pset so I decided to move on to the next week – Dave G Mar 24 '17 at 1:17
  • Your code seems to be unindented. – Ianardo Mar 24 '17 at 3:19
  • The indenting issues are only here on stack exchange because when I pasted my code the formatting was off. The code in my cs50 IDE is properly formatted (I double checked after you posted this) – Dave G Mar 24 '17 at 18:15
  • Can I ask why you are doing this: from register.html import * – Ianardo Mar 26 '17 at 2:45
0

Really sorry about this coming so late but I had the same issue yesterday and this is exactly what I did.

When running your program (I mean after exporting or setting your flask app) make sure to change your directory to the current folder which the program can be found (i.e the folder which housed the .py file). On window you have something like

cd..
cd program files\desired directory

Then now run your app. That should work well.

Thanks

You must log in to answer this question.

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