0

I get below errors from check50:

:( buy handles invalid ticker symbol
    application raised an exception (see the log for more details)
:( buy handles fractional, negative, and non-numeric shares
    application raised an exception (see the log for more details)
:( buy handles valid purchase
    expected to find "112.00" in page, but it wasn't found
:| sell page has all required elements
    can't check until a frown turns upside down
:| sell handles invalid number of shares
    can't check until a frown turns upside down
:| sell handles valid sale
    can't check until a frown turns upside down

Below is my "buy" code:

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

    if request.method == "POST":
        symbol = request.form.get("symbol")
        search = lookup(symbol)
        price = search["price"]
        shares = int(request.form.get("shares"))

        if not symbol or search == None:
            return apology ("No or Invalid symbol")

        # Ensure valid number of shares.Render an apology if the input is not a positive integer
        if shares < 1:
            return apology("Shares must be positive number", 400)

        ####
        # Query the database for the current user to make sure the user can afford the current stock
        ####

        # Query the database for available cash
        current_user_row = db.execute("SELECT cash FROM users WHERE id = ?" , session["user_id"])
        current_user_cash = current_user_row[0]["cash"]
        # Value of the stock that the user wants to buy
        stock_value_asked =  price * shares

        # # Cash Balance
        cash_after = current_user_cash - stock_value_asked

        # # Grand Total (Stocks Value + Cash)
        grand_total = stock_value_asked + cash_after


        # if user's current cash balance is less then the stock value asked for
        if current_user_cash < stock_value_asked:
            return apology("Insufficient Balance", 400)

        # Select user shares of specified symbol from the database
        user_shares = db.execute("SELECT share_amount FROM Purchase WHERE person_id    = ? AND stocks_owned = ?", session["user_id"], symbol )

        # if user has no shares of the symbol, create new stock
        if not user_shares:
           insert = db.execute("INSERT INTO Purchase (person_id,stocks_owned,share_amount,price_per_stock,remaining_cash,stock_value_asked,grand_total) VALUES(?,?,?,?,?,?,?)",  session["user_id"],symbol,shares,price,cash_after,stock_value_asked,grand_total)

        # if user does, increment the shares count
        else:
            shares_count = user_shares[0]["share_amount"] + shares
            db.execute("UPDATE Purchase SET share_amount = ? WHERE person_id = ?", shares_count,session["user_id"])
            db.execute("UPDATE Purchase SET remaining_cash = ? WHERE person_id = ?", cash_after,session["user_id"])

        # Update cash in users Table
        db.execute("UPDATE users SET cash = ?  WHERE id = ?", cash_after , session["user_id"])


        # Update History Table
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db.execute("INSERT INTO Histories (user_id,stocks_owned,share_amount,price_per_stock,transacted) VALUES(?,?,?,?,?)",  session["user_id"],symbol,shares,price,now)


        return redirect("/")



Below is my "sell" code:

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

    elif request.method == "POST":
        symbol = request.form.get("symbol")
        search = lookup(symbol)
        price = search["price"]
        shares = int(request.form.get("shares"))

        # if the input is blank or the symbol does not exist
        if not symbol or search == None:
            return apology ("No or Invalid symbol")

        # if the user does not own any shares of that stock
        user_shares_list = db.execute("SELECT share_amount FROM purchase WHERE stocks_owned = ? AND person_id = ?", symbol,session["user_id"])
        user_shares_int = user_shares_list[0]["share_amount"]

        if not user_shares_list or user_shares_int < shares:
            return apology("No shares OR Insufficient shares", 400)

        else:
            cash = db.execute("SELECT remaining_cash FROM Purchase WHERE person_id = ?", session["user_id"])
            users_cash = cash[0]["remaining_cash"]

            users_cash += shares * price

            db.execute("UPDATE Purchase SET remaining_cash = ? WHERE person_id = ?", users_cash,session["user_id"])

            db.execute("UPDATE users SET cash = ? WHERE id = ?", users_cash,session["user_id"])

            current_shares = user_shares_int - shares

            db.execute("UPDATE Purchase SET share_amount = ? WHERE person_id = ?", current_shares,session["user_id"])

            # Update History Table
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            db.execute("INSERT INTO Histories (user_id,stocks_owned,share_amount,price_per_stock,transacted) VALUES(?,?,?,?,?)",  session["user_id"],symbol,-shares,price,now)

            return redirect("/")

I can't seem to find whats the problem with the code, because it works fine. Can someone please specify, what mistake am I doing.?

1

If the symbol entered is invalid, this line price = search["price"] gives error "TypeError: 'NoneType' object is not subscriptable" because lookup returns None.

Code will give Value error here shares = int(request.form.get("shares")) if shares is non-numeric. Further, casting shares to int is not sufficient to ensure that shares is "not fractional"; it will process an input of 22.5 and it should not. Have a look at the isnumeric string method

The code works fine if input is "perfect". Try it with an invalid stock symbol (eg "CS50") or a non-numeric shares (eg "X"). flask will give "500 Internal Server Error". The traceback in the flask log will point you to the offending line(s) of code.

6
  • So this works: ``` symbol = request.form.get("symbol") if not symbol: return apology ("No or Invalid symbol") search = lookup(symbol) price = search["price"] shares = int(request.form.get("shares")) ``` and this doesn't: ``` symbol = request.form.get("symbol") search = lookup(symbol) price = search["price"] shares = int(request.form.get("shares")) if not symbol: return apology ("No or Invalid symbol") ``` Why.?
    – Khan
    Aug 8 at 8:23
  • When lookup returns None, ie when the symbol is invalid, search["price"] does not exist and gives an error. Aug 8 at 10:12
  • Fixed the last problem. And how do I check for int: ``` symbol = request.form.get("symbol") if not symbol: return apology ("No or Invalid symbol",400) search = lookup(symbol) price = search["price"] shares = int(request.form.get("shares")) # Ensure valid number of shares.Render an apology if the input is not a positive integer if shares < 1 and shares != int(request.form.get("shares")): return apology("Shares must be positive number", 400) ```
    – Khan
    Aug 8 at 12:17
  • Have a look at isnumeric string method Aug 8 at 14:18
  • still not working: ``` shares = int(request.form.get("shares")) if shares < 1: return apology("Shares must be positive number", 400) if shares.isnumeric == False: return apology("Shares must be non-decimal number", 400) ```
    – Khan
    Aug 8 at 14:34

You must log in to answer this question.

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