-
-
Save anonymous/4b64b3d28aa19568d4bfbb0039cc47d8 to your computer and use it in GitHub Desktop.
application.py - shared from CS50 IDE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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