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.
Return
?float()
aroundrequest.form.get("quantity")
help? Maybe yourcost
is not a number.int
. Likecost = quote["price"] * int(request.form.get("quantity"))
. I suspect your code runs into if, elif, but none of the conditions match sincecost
is not a number, a finalelse
would trigger. Maybe you should also return an apology whennot str.isdigit(request.form.get("quantity"))
.