0

I'm at the last check for the 'buy' part and I keep getting:

:( buy handles valid purchase expected to find "9,888.00" in page, but it wasn't found

I'm pretty sure that number is supposed to be on the index page, since that's the page you get redirected to after a purchase. I don't know what that number represents, but I think it's the value of your stocks, or cash, or the total. The problem is: I have all those values on my index page but I'm not passing the check.

Also: sometimes a change in my index part in application.py will cause the login to fail (for example: displaying the last transaction of a user in index made login fail). I have no idea why, because you get login pre-made and I edited nothing from login.

I'm really at a loss here. Can anyone make sense of this? My index and buy code can be seen below.

INDEX:

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    user = db.execute("SELECT * FROM users WHERE id == :userid", userid=session["user_id"])[0]
    owned = db.execute("SELECT * FROM owned WHERE user_id == :userid", userid=session["user_id"])

    i = 0
    stonks = 0
    portdict = []
    for row in owned:
        indprice = lookup(owned[i]["symbol"])["price"]
        stonks = stonks + round(indprice * owned[i]["shares"], 2)
        portdict.append({"symbol": owned[i]["symbol"], "shares": owned[i]["shares"], "price": usd(indprice), "total": usd(round(owned[i]["shares"] * indprice, 2))})
        i += 1
        
    return render_template("index.html", user=user, owned=owned, portdict=portdict, stonks=stonks)

INDEX:

{% extends "layout.html" %}

{% block title %}
    Index
{% endblock %}

{% block main %}

    My account:<br /><br />

    Username: {{ user["username"] }}<br />
    Cash: ${{ user["cash"] }}<br />
    Stonks: ${{ stonks }}<br />
    Total Funds: ${{ user["cash"] + stonks }}
    <br /><br />


    <tr>
        <th>Stock</th>
        -
        <th>Ind Price</th>
        -
        <th>Shares</th>
        -
        <th>Tot Price</th>
    </tr><br />

{% for row in portdict %}
    <tr>
        <td>{{ row["symbol"] }}</td>
        -
        <td>{{ row["price"] }}</td>
        -
        <td>{{ row["shares"] }}</td>
        -
        <td>{{ row["total"] }}</td>
    </tr><br />
{% endfor %}
<br /><br />

{% endblock %}

BUY:

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    cash = db.execute("SELECT cash FROM users WHERE id == ?", session["user_id"])[0]["cash"]

    if request.method == "POST":

        if (not request.form.get("shares")) or (not request.form.get("symbol")):
            return apology("Not all boxes are filled in.")

        buydict = lookup(request.form.get("symbol"))
        if not buydict:
            return apology("No valid symbol given.")

        if not request.form.get("shares").isdigit():
            return apology("No digit given.")

        shares = int(request.form.get("shares"))

        symbol = request.form.get("symbol")
        price = buydict["price"]
        date = datetime.now()

        cost = price * shares
        newcash = cash - cost
        if newcash < 0:
            return apology("Not enough cash.")
        else:
            db.execute("UPDATE users SET cash = :newcash WHERE id == :userid", newcash=round(newcash, 2), userid=session["user_id"])
            db.execute("INSERT INTO transactions (user_id, symbol, price, shares, date) VALUES (:userid, :symbol, :price, :shares, :date)", userid=session["user_id"], symbol=symbol, price=usd(price), shares=shares, date=date)
            portfolio = db.execute("SELECT shares FROM owned WHERE symbol == :symbol AND user_id == :userid", symbol=symbol, userid=session["user_id"])
            if not portfolio:
                db.execute("INSERT INTO owned (user_id, symbol, shares) VALUES (:userid, :symbol, :shares)", userid=session["user_id"], symbol=symbol, shares=shares)
            else:
                db.execute("UPDATE owned SET shares=shares+:shares WHERE symbol=:symbol AND user_id==:userid", shares=shares, symbol=symbol, userid=session["user_id"])

        return redirect("/")

    else:
        return render_template("buy.html", cash=cash)

BUY:

{% extends "layout.html" %}

{% block title %}
    Buy
{% endblock %}

{% block main %}

    <h2>Buy</h2><br />

    Your Cash: ${{ cash }}<br /><br />

    <form action="/buy" method="post">
        <input name="symbol" type="text" placeholder="Symbol">
        <input name="shares" type="number" placeholder="Amount" min="1" step="1">
        <button type="submit">Submit</button>
    </form>

{% endblock %}

1 Answer 1

0

Are "all those numbers" formatted correctly? It looks like neither user.cash nor Total Funds is formatted as with usd. The check is using some kind of pattern matching, so the output must match exactly (comma separated thousands; 2 decimal places).

Please add some color to "cause login to fail". Does it give an error? If so what? Is the traceback in the flask console helpful?

1
  • Yes! I didn't format cash, stock value and total value of the user with usd(), can't believe I missed that. Now it works, thanks!
    – Fijn
    Commented Jul 19, 2021 at 11:29

You must log in to answer this question.

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