:( buy handles valid purchase

expected to find "112.00" in page, but it wasn't found

Log sending POST request to /login sending POST request to /buy checking that "112.00" is in page

Above is the output of the check50 error .

The website works totally fine . I checked some questions but it was about usd format and i checked that my index page prints usd format .

Here is my code of index and buy :


def index():
    """Show portfolio of stocks"""


    # Query database to display information
    stocks = db.execute("SELECT stock, shares FROM portfolio WHERE id = :u_id", u_id = session["user_id"])

    # total balance
    grand_total = 0

    # data
    data = []

    # stock info
    for stock in stocks:

        # look up a stock’s current price
        stock_data = lookup(stock["stock"])

        # Sum of each holding
        stock_shares = db.execute("SELECT SUM(price), purchase_date FROM portfolio WHERE id = :u_id AND stock = :stock", u_id = session["user_id"],
                                    stock = stock_data["symbol"])
        if stock_shares[0]['SUM(price)'] == 0:

            # The data of stock
            info_stock = {}

            info_stock["Shares"] = stock["shares"]
            info_stock["Name"] = stock_data["name"]
            info_stock["Symbol"] = stock["stock"]
            info_stock["Paid"] = stock_shares[0]["SUM(price)"]
            info_stock["Price of the share"] = stock_data["price"]
            info_stock["Purchase date"] = stock_shares[0]["purchase_date"]

            grand_total += info_stock["Price of the share"] * info_stock["Shares"]

    # Balance
    cash = db.execute("SELECT cash FROM users WHERE id = :u_id", u_id = session["user_id"])
    balance = cash[0]["cash"]

    # updating grand total
    grand_total += balance

    # Converting price into usd format
    for i in range(len(data)):
            data[i]['Paid'] = usd(data[i]['Paid'])
            data[i]['Price of the share'] = usd(data[i]['Price of the share'])

    return render_template("index.html", data=data, balance=usd(balance), grand_total=usd(grand_total))

@app.route("/buy", methods=["GET", "POST"])

def buy():
    """Buy shares of stock"""

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

    # Ensure symbol was submitted
    if not request.form.get("symbol"):
        return apology("Please enter the stock's symbol", 400)

    # Ensure no. of shares was submitted
    if not request.form.get("shares") or not isinstance(request.form.get("shares"), int):
        return apology("Please enter the no. of shares you want to buy", 400)

    # look up a stock’s current price
    quote = lookup(request.form.get("symbol"))

    # Check input is valid
    if not quote:
        return apology("Invalid Symbol", 400)

    # Check if the shares is positive
    elif int(request.form.get("shares")) < 0:
        return apology("Invalid no. of shares", 400)

        # Check if the user can afford the stock
        afford = db.execute("SELECT cash FROM users WHERE id = 1")

        purchase = float(request.form.get("shares")) * quote["price"]

        if afford[0]["cash"] < purchase:
            return apology("Can't afford", 400)

            # Updating portfolio
            buying = db.execute("INSERT INTO portfolio (shares, stock, purchase_date, price, id) VALUES(:shares, :stock, :date , :price, :u_id) "
            , shares=request.form.get("shares"), stock=quote["symbol"], date=datetime.now(), price=purchase, u_id = session["user_id"])

            # Updating history
            history = db.execute("INSERT INTO buyhistory (name, symbol, shares, paid, date, id) VALUES(:name, :symbol, :shares, :paid, :date, :u_id) "
                                    , name= quote["name"], symbol=quote["symbol"], shares=float(request.form.get("shares")), paid=purchase,
                                            date=datetime.now(), u_id=session["user_id"])

            # Updating the cash
            paying = db.execute("UPDATE users SET cash = cash - :purchase WHERE id = :u_id", purchase=purchase, u_id = session["user_id"])

            flash("Purchased successfully ")
            return redirect("/")

# User reached route via GET (as by clicking a link or via redirect)
    return render_template("buy.html")

And here is the index .html :

{% extends "layout.html" %}

{% block title %}
    Stock Information
{% endblock %}

{% block main %}
{% with messages = get_flashed_messages() %}
         {% if messages %}
               {% for message in messages %}
               <li<{{ message }}</li>
               {% endfor %}
         {% endif %}
      {% endwith %}
<table class="table">
    <thead class="thead-dark">
        <th scope="col">Shares</th>
        <th scope="col">Name</th>
        <th scope="col">Symbol</th>
        <th scope="col">Paid</th>
        <th scope="col">Price of the Share</th>
        <th scope="col">Purchase Date</th>
  {% for info_stock in data %}
        {% for key, value in info_stock.items() %}
        <td>{{ value }}</td>
        {% endfor %}
  {% endfor %}
  <table class="table">
  <thead class="thead-light">
      <th scope="col">#</th>
      <th scope="col">Cash</th>
      <th scope="col">Total</th>
      <td>{{ balance }}</td>
      <td>{{ grand_total }}</td>
{% endblock %}

Hi and welcome to the forum.

I suspect the problem lies here or not isinstance(request.form.get("shares"), int) in the buy route.

From the spec [emphasis mine]:

Require that a user input a number of shares, implemented as a text field whose name is shares. Render an apology if the input is not a positive integer.

If you are verifying the input in buy.html, good on ya! Better UX! Users will thank you. check50, on the other hand, may punish you. Alas, this course is not about UX. And since the above is in the buy spec, the black-magic-box that is check50 is somehow ensuring that. This buy function does not explicitly test the "positive integer" condition.

FWIW I cannot get the not isinstance to return anything but False in my repro case. type(request.form.get("shares")) always returns str (tested with both Chrome and Firefox). I cannot explain why it works in your environment.

You must log in to answer this question.

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