Skip to content

Instantly share code, notes, and snippets.

/application.py Secret

Created March 17, 2017 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4b64b3d28aa19568d4bfbb0039cc47d8 to your computer and use it in GitHub Desktop.
Save anonymous/4b64b3d28aa19568d4bfbb0039cc47d8 to your computer and use it in GitHub Desktop.
application.py - shared from CS50 IDE
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock."""
# if user arrived by submitting a form via POST
if request.method == "POST":
# check symbol entered & valid
symbol = request.form.get("symbol")
result = lookup(symbol)
if result == None:
return apology("invalid symbol")
if symbol == "":
return apology("must enter symbol")
# check shares entered correctly
try:
shares = int(request.form.get("shares"))
except ValueError:
return apology("invalid quantity")
if shares == "":
return apology("must enter quantity")
if shares <= 0:
return apology("invalid quantity")
# check user can afford total cost of shares
total = result["price"] * shares
rows = db.execute("SELECT cash FROM users WHERE id = :current", current=session["user_id"])
cash = rows[0]["cash"]
if total > cash:
return apology("too broke")
# record purchase
purchase = db.execute("INSERT INTO transactions (user_id, symbol, name, shares, price, total) VALUES (:user_id, :symbol, :name, :shares, :price, :total)",
user_id=session["user_id"], symbol=result["symbol"], name=result["name"], shares="shares", price=result["price"], total="total")
# dummy page until index is built
return apology("success")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment