Cs 50 finance, buy function

Hello everyone,
I have troubles on my cs50 finance. Im stuck at the buy function.
I get internal server error, 500. Everytime I submit. All the errors work, like if I type in wrong name or invalid value, it gives me the implemented error back. But I just cant find out whats wrong in the code.
Anyone has any idear?

@app.route("/buy", methods=[“GET”, “POST”])
def buy():
if request.method == “POST”:

    user_id = session["user_id"] #get id
    symbol = request.form.get("symbol") #what to buy
    shares = int(request.form.get("shares")) #how many to buy

    #check if symbol is entered
    if not symbol:
        return apology("must provide symbol", 403)

    # check if symbol is valid
    if lookup(symbol) is None:
        return apology("invalid symbol provided", 403)

    # check if number of shares is entered
    if not shares:
        return apology("must provide number of shares", 403)

    # allow only positive values.
    if shares <= 0:
        return apology("must provide positive integer", 403)

    cash = db.execute("SELECT * FROM users WHERE id = (:session)", session=user_id)[0]["cash"] #defines how much cash user has
    price = lookup(symbol)["price"]
    totalvalue = shares * price #total value number of stocks * price per stock
    total = cash - totalvalue #total cash - price of stocks

    db.execute("INSERT INTO track (what, howmany, who) VALUES (:symbol, :shares, :session)", symbol=symbol, shares=shares, session=user_id)
    db.execute("UPDATE users SET cash = (:total) WHERE id = (:session)", session = user_id, total=total)
    return redirect("/")

    return render_template("buy.html")
1 Like

The code looks like you’re using Flask. Flask will send a 500 error if there’s an unhandled exception while handling the request. If the errors you’re explicitly handling work the problem is likely somewhere in the code from cash = db.execute(...) to return redirect("/").

The exception and its trace should be logged on the server side. Look at that to figure out what’s wrong, or if you have trouble understanding the exception post it here. :slightly_smiling_face:

Oh, and:

This will raise a TypeError if the shares parameter is missing, because int(None) is invalid.

1 Like

Hello, Thanks a lot for your answer. I appreciate it.
I had a look again at the code. But I’m not quiet sure what you mean by exception, can you give me some specifics?

Here is the html code the function is refering to:

{% extends “layout.html” %}

{% block title %}
{% endblock %}

{% block main %}

    <button class="btn btn-primary" type="submit">Buy</button>

{% endblock %}

And here is the Lookup function, I assume the problem is maybe there?

def lookup(symbol):
“”“Look up quote for symbol.”""

# Contact API
    api_key = os.environ.get("API_KEY")
    response = requests.get(f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}")
except requests.RequestException:
    return None

# Parse response
    quote = response.json()
    return {
        "name": quote["companyName"],
        "price": float(quote["latestPrice"]),
        "symbol": quote["symbol"]
except (KeyError, TypeError, ValueError):
    return None
1 Like

Exceptions are a core concept of Python an many other programming languages. They occur when something that’s syntactically valid can’t be executed, for example a division by zero:

>>> 1 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Check the Python tutorial chapter Errors and Exceptions for more details.

My main point is that the Flask server should log an exception message (vaguely similar to the division by zero example above), and that message should tell you what problem occurred where, as in, which file and line and from where it was called.


maybe because I multiply an integer with a float?

That shouldn’t be an issue in Python. As I said, try to find the logged exception (should be in the output of the server). That should give you a description of what happened, much better than guessing. :wink:

How do I find that? Sorry I’m quiet new to programming :see_no_evil:

Usually wherever you start the server. For a course project I assume you’re using a command like flask run. In that case the logs (including exceptions) should end up in the terminal you used to run that command. Or if you use an IDE and run the server from there it might capture the output and show it somewhere.

The general answer is “it depends on the server configuration”, but I assume you’re using one of the simple options here. :wink:

Thanks a lot. Now I found the bug quiet easily. I can’t believe I changed my code in any possible ways. And the bug was that in my SQL file one column was named “how many” and in the code it was “howmany”.

1 Like