Here's my code for the buyindex application:
"""Buy shares ofdef stock"""
index():
# User reached route via"""Show POSTportfolio (asof bystocks"""
# submittingUser areached formpage via POST)redirect
if request.method == "POST""GET":
# EnsureLookup stockusername symboland wascash submitted
of current user and ifstore notin request.form.get("symbol"):variables
user return= apologydb.execute("Missing"SELECT stock'susername symbol",FROM 400)
users WHERE id = else:
# Ensure float number ofuser_id", sharesuser_id was= submittedsession["user_id"])
try:
cash = db.execute("SELECT cash FROM users WHERE id = :user_id", sharesuser_id = float(request.form.get("shares")session["user_id"])
# Lookup exceptcurrent ValueError:
portfolio of user and store in variable sumshares
sumshares return= apologydb.execute("Please submit number"SELECT ofstock, shares"symbol, 400SUM(numshares)
, price, valuestocks FROM portfolio WHERE #user_id Ensure= positive:user_id integerGROUP numberBY ofstock", sharesuser_id was= submittedsession["user_id"])
# Define variable iffor (sharestotal %value 1)of !=all 0stocks orand (sharesinitialize <to 0):zero
return apology("Please submit number oftotalvaluestocks shares",= 400)0
# Update #sumshares Checkwith iflatest stock existsprices
for i elifin (lookuprange(request.form.getlen("symbol"sumshares)) == None):
sumshares[i]['price'] return= apologylookupindex("Stock does not exist", 400sumshares[i]['symbol'])
else:
# Check stock and store info in variables
sumshares[i]['valuestocks'] = stocksumshares[i]['price'] =* lookup(request.form.getsumshares[i]['SUM("symbol")numshares)']
stocknametotalvaluestocks = stock['name']
totalvaluestocks + sumshares[i]['valuestocks']
# Update stockpriceto =format stock['price']USD
stocksymbolsumshares[i]['price'] = stock['symbol']usd(sumshares[i]['price'])
totalvaluesumshares[i]['valuestocks'] = usd(stockprice * sharessumshares[i]['valuestocks'])
# Calculate grand total
# Calculategrandtotal current= datecash[0]['cash'] and+ timetotalvaluestocks
# format values to USD
nowgrandtotal = datetime.nowusd(grandtotal)
dcash[0]['cash'] = now.dateusd(cash[0]['cash'])
ttotalvaluestocks = now.timeusd(totalvaluestocks)
# Lookup user's available cash and storeGenerate inindex variablepage
return render_template("index.html", user = user[0]['username'], user_cashcash = db.execute("SELECT cashcash[0]['cash'], FROMtotalvaluestocks users= WHEREtotalvaluestocks, idsumshares = :user_id"sumshares, user_idgrandtotal = session["user_id"]grandtotal)
# User reached route via POST (as #by Ensuresubmitting usera hasform enoughvia cashPOST)
elif request.method == "POST":
# Check for valid input
if totalvalue > user_cash[0]['cash']try:
extracash return= apologyfloat("Not enough cash to buy", 403request.form.get("extracash"))
except elseValueError:
return #apology("Please addtype transactionin tovalid thecash portfolioamount", table403)
# Add cash to user
resultcurrent = db.execute("INSERT INTO portfolio (user_id, stock, symbol, price, numshares, valuestocks, date, time, buyorsell) VALUES(:user_id, :stock,"SELECT :symbol,cash :price,FROM :numshares,users :valuestocks,WHERE :date,id :time,= :buyorsell)"user_id", user_id = session["user_id"], stock = stockname, symbol = stocksymbol, price = stockprice, numshares = shares, valuestocks = totalvalue, date = d, time = t, buyorsell = 'BUY')
if result != None:
db.execute("UPDATE users SET cash = :cash WHERE id = :user_id", cash = user_cash[0]['cash']current[0]['cash'] -+ totalvalueextracash, user_id = session["user_id"])
# RedirectReturn user to index
flash('BUYhome SUCCESSFUL')page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("buy.html")
Looking at the log file, there is a problem with the application trying to multiply two variables, one of which is of type 'NonType' and the other is an int. Since there is only one line of code in my whole program where I multiply two values, one of them being an int it should result from:
totalvaluesumshares[i]['valuestocks'] = (stockpricesumshares[i]['price'] * sharessumshares[i]['SUM(numshares)']
But given all the other earlier IF conditions I cannot see how either stockprice
or shares
can haveThis line of code is meant to update the value None
and so is of typethe stock with the current price info. So instead of showing the historic price NonType
(at time of purchase), it shows the current price.
In the buy section there is another multiplication, but that multiplication has no ints as input.