0

My functions seens to work fine, but when i have that redirect the user to the homepage (redirect("/")) the application crash and show the error message: 500 internal server error and I don't know if I'm wrong in the function (def index()) or in the redirect("/"). How may i solve this?? Thanks in advance. Here is my fully code (i don't even know how to publish a code here sorry):

import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@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:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    user = db.execute("SELECT * FROM users WHERE id = :id",id=session["user_id"])[0]["cash"]
user = round(user, 2)
transactions = db.execute("SELECT * FROM portifolio WHERE id = :id", id=session["user_id"])

# save in list
stocks = []

# get all data and put in dict
for trans in transactions:
    symbol = trans["stock"]
    shares = trans["shares"]
    stock_data = lookup(symbol)

    temp_dict = {
        "symbol": symbol,
        "name": stock_data["name"],
        "shares": shares,
        "price": round(stock_data["price"], 2),
        "total": round(stock_data["price"] * shares, 2)
    }

    stocks.append(temp_dict)

# get users current wealth
total_money = round(user + sum([stock["total"] for stock in stocks]), 2)

return render_template("index.html", stocks=stocks, money=total_money, user=user)


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    if request.method == "POST":
        symbol = request.form.get("symbol")
        shares = request.form.get("shares")
        quote = lookup(symbol)
        user_id = session["user_id"]

        if quote == None:
            return apology("invalid symbol", 400)

        if not isinstance(shares, int):
            return apology("input is not a positive integer", 400)

        if shares <= 0:
            return apology("can't buy a negative number of shares or 0 share", 400)

        rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id)

        total_cash = rows[0]["cash"]
        price = quote["price"]

        cost = price * shares

        if cost > total_cash:
            return apology("you don't have enough funds")

        db.execute("UPDATE users SET cash = cash - :price WHERE id = :user_id", price=cost, user_id=user_id)
        db.execute("INSERT INTO transactions (user_id, symbol, shares, price) VALUES(:user_id, :symbol, :shares, :price)", user_id=user_id, symbol=symbol, shares=shares, price=price)

        flash("Bought!")
        return redirect("/")

    else:
        return render_template("buy.html")


@app.route("/history")
@login_required
def history():
    """Show history of transactions"""

    user_id=session["user_id"]

    transactions = db.execute("SELECT symbol, shares, price_per_share, created_at FROM transactions WHERE user_id = :user_id ORDER BY created_at ASC", user_id=user_id)

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


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

    # Forget any user_id
    session.clear()

    # 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", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # 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 check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

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

        # Redirect user to home page
        return redirect("/")

    # 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("/")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""

    symbol = request.form.get("symbol")

    if request.method == "POST":
        quote = lookup(symbol)

        if quote == None:
            return apology("invalid symbol", 400)

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

    else:
        return render_template("quote.html")

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

    if request.method == 'POST':

        username = request.form.get('username')
        password = generate_password_hash(request.form.get('password'))
        confirmation = request.form.get("confirmation")

        if not username:
            return apology("must provide username", 400)

        elif not request.form.get("password"):
            return apology("must provide password", 400)

        elif not confirmation:
            return apology("must provide equal password", 400)

        elif request.form.get("password") != confirmation:
            return apology("passwords do not match", 400)

        double_username= db.execute("SELECT username FROM users where username = :username", username=username)
        if double_username:
            return apology("username already taken", 400)

        row = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=username, hash=password)
        session["user_id"] = row
        flash("Registered!")
        return redirect("/")

    else:
        return render_template("register.html")

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""

    if request.method == "POST":
        symbol = request.form.get = ("symbol")
        shares = request.form.get("shares")
        user_id=session["user_id"]
        quote = lookup(symbol)

        if quote == None:
            return apology("invalid symbol", 400)

        if quote == None:
            return apology("invalid symbol", 400)

        if not isinstance(shares, int):
            return apology("input is not a positive integer", 400)

        if shares <= 0:
            return apology("can't have a negative number of shares or 0 share", 400)

        stock = db.execute("SELECT SUM(shares) as total_shares FROM transactions WHERE user_id = :user_id AND symbol = :symbol GROUP BY symbol", user_id=user_id, symbol=symbol)

        if len(stock) != 1 or stock[0]["total_shares"] <= 0 or stock[0]["total_shares"] < shares:
            return apology("can't sell a negative number of shares or 0 share or more than you own", 400)

        rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id)

        total_cash = rows[0]["cash"]
        price = quote["price"]

        cost = price * shares

        db.execute("UPDATE users SET cash = cash + :price WHERE id = :user_id", price=cost, user_id=user_id)
        db.execute("INSERT INTO transactions (user_id, symbol, shares, price) VALUES(:user_id, :symbol, :shares, :price)", user_id=user_id, symbol=symbol, shares=-shares, price=price)

        flash("Sold!")
        return redirect("/")

    else:
        stocks = db.execute("SELECT symbol, SUM(shares) as total_shares FROM transactions WHERE user_id = :user_id GROUP BY symbol HAVING total_shares > 0", user_id=user_id)

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


def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)


# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)

Terminal error Site error

~/finance/ $ export API_KEY=pk_1d9ce2d967864e6cb4696426a0902311
~/finance/ $ flask run
 * Serving Flask app "application.py" (lazy loading)
 * Environment: development
 * Debug mode: off
 * Running on https://b32edcbd-c7d9-46fc-883b-2d754eec3461-ide.cs50.xyz:8080/ (Press CTRL+C to quit)
 * Restarting with stat
INFO:werkzeug:192.168.228.165 - - [01/May/2020 16:18:33] "GET / HTTP/1.0" 302 -
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:33] "GET /login HTTP/1.0" 200 -
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:34] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:45] "GET /register HTTP/1.0" 200 -
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:45] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:cs50:INSERT INTO users (username, hash) VALUES('top', 'pbkdf2:sha256:150000$yU2ahu9E$49206c3e7959c998b394c9cecc0f6a507c1fbf18565fbed2796b626574d34ade')
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:51] "POST /register HTTP/1.0" 302 -
DEBUG:cs50:SELECT * FROM users WHERE id = 3
DEBUG:cs50:SELECT * FROM portifolio WHERE id = 3
ERROR:application:Exception on / [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/finance/application.py", line 74, in index
    return render_template("index.html", stocks=stocks, money=total_money, user=user)
  File "/usr/local/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
    ctx.app,
  File "/usr/local/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
    rv = template.render(context)
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "/home/ubuntu/finance/templates/index.html", line 1, in top-level template code
    {% extends "layout.html" %}
  File "/home/ubuntu/finance/templates/layout.html", line 63, in top-level template code
    {% block main %}{% endblock %}
  File "/home/ubuntu/finance/templates/index.html", line 22, in block "main"
    <td>{{ cash_remaining | usd }}</td>
  File "/home/ubuntu/finance/helpers.py", line 63, in usd
    return f"${value:,.2f}"
TypeError: unsupported format string passed to Undefined.__format__
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:51] "GET / HTTP/1.0" 500 -
INFO:werkzeug:192.168.143.107 - - [01/May/2020 16:18:51] "GET /static/styles.css HTTP/1.0" 200 -

this is the prompt at the moment

  • Please edit the question and 1) format the code. Select the code and hit the {} button in the format bar; and 2) add the traceback information that appears in the flask terminal. – DinoCoderSaurus Apr 29 '20 at 9:40
  • DinoCoderSaurus I made the changes you commented, may you help me please?? – Leonardo Manzini Apr 29 '20 at 14:19
0

The traceback is telling you everything you need to know. Down at the bottom there is a Runtime Error. Since it's an image and not text I cannot copy/paste it here. There is no table named transactions in the database that the application is connected to. Remember sqlite3 will create a new database if the named one is not found, so perhaps the table was created in a db in a different directory. Verify that transactions table exists in finance.db in ~/finance

  • I made a lot of fixes, but the same error still anoying me :( – Leonardo Manzini May 1 '20 at 16:21
  • i"ll post the actual messages at the prompt – Leonardo Manzini May 1 '20 at 16:21
  • The usd function takes a float as its argument; based on the error message one would assume cash_remaining is a string: "TypeError: unsupported format string passed to Undefined.__format_". Impossible to say, because there is no other occurrence in the posted code. – DinoCoderSaurus May 1 '20 at 19:42
  • Thanks i could fix it!!! – Leonardo Manzini May 2 '20 at 1:09

You must log in to answer this question.

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