0

After selecting Buy, when I submit form after filling stock symbol and quantity. The page just hangs and do not respond. Ideally it should take me to index page after buying the stock.

Below is the code.

buy function in app.py

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock."""
    if request.method == "POST":
        stock=request.form.get("symbol")
        quote=lookup(stock)
        if quote == None:
            return apology("Invalid stock symbol")
        userId = session["user_id"]
        cost = quote["price"] * request.form.get("quantity")
        cash =  db.execute("SELECT cash FROM users WHERE id = :id", id=userId)
        if(cost > cash[0]["cash"]):
            return apology("Insufficent Funds")
        elif(cost <= cash[0]["cash"]):
            #check if symbol is already in table
            stockId = db.execute("SELECT id FROM symbols WHERE sym = :sym", sym=quote["symbol"])
            if len(stockId) == 0:               #first time purchase
                result = db.execute("INSERT INTO symbols (sym, name) VALUES(:sym, :name)",sym=quote["symbol"],name=quote["name"])
                stockId = db.execute("SELECT id FROM symbols WHERE sym = :sym", sym=quote["symbol"])
            purchase = db.execute("INSERT INTO transactions (uId, symId, sharesCount ) VALUES(:uId, :symId, :sharesCount)",uId=userId,symId=stockId[0]["id"],sharesCount=request.form.get("quantity"))
            updateCash = db.execute('UPDATE users SET cash=? WHERE id=?', ( cash[0]["cash"] - cost, userId ))       
            return render_template("index.html")
    else:
        return render_template("buy.html")

buy.html

{% extends "layout.html" %}

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

{% block main %}
    <form action="{{ url_for('buy') }}" method="post">
        <fieldset>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="symbol" type="text"/>
                <input autocomplete="off" autofocus class="form-control" class="form-control" name="quantity" placeholder="quantity" type="text"/>
            </div>
        </fieldset>
    </form>
{% endblock %}

I am using almost the same method for quote and its working.

The table structure I have in DB -

transactions

CREATE TABLE transactions( tId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, uId INTEGER NOT NULL, symId INTEGER NOT NULL, sharesCount INTEGER NOT NULL, timestamp datetime default current_timestamp, FOREIGN KEY(uId) REFERENCES users(id), FOREIGN KEY(symId) REFERENCES symbols(id) )

symbols

CREATE TABLE 'symbols' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'sym' TEXT NOT NULL, 'name' TEXT NOT NULL)

Please let me know in case of any other detail is needed.

Thanks for help.

  • I don't see a submit button, how do you submit? Just pressing Return? – Blauelf Nov 27 '17 at 12:43
  • Yes I do not have submit button, I was hoping that return or pressing enter will work. – Santosh Prasad Nov 27 '17 at 13:04
  • It seems to work. Wasn't aware it would work like this :) Other question: Does wrapping some float() around request.form.get("quantity") help? Maybe your cost is not a number. – Blauelf Nov 27 '17 at 13:15
  • I don't know its necessary as python should do type casting. BTW how i should change it to float? – Santosh Prasad Nov 27 '17 at 13:19
  • Or rather int. Like cost = quote["price"] * int(request.form.get("quantity")). I suspect your code runs into if, elif, but none of the conditions match since cost is not a number, a final else would trigger. Maybe you should also return an apology when not str.isdigit(request.form.get("quantity")). – Blauelf Nov 27 '17 at 13:38

You must log in to answer this question.

Browse other questions tagged .