Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- """Buy shares of stock."""
- if request.method == "GET":
- return render_template("buy.html")
- # if user reached route via POST
- if request.method == "POST":
- # ensure symbol was submitted
- if not request.form.get("symbol") and request.form.get("number_stocks"):
- return apology("symbol required")
- else:
- #lookup the stock using the symbol and define vars
- details = lookup(request.form.get("symbol"))
- symbol = request.form.get("symbol")
- price = details["price"]
- quantity = int(request.form.get("number_stocks"))
- total = price * quantity
- user = session["user_id"]
- #ensure the stock is valid
- if price == None:
- return apology("this stock is not valid")
- else:
- #get cost of stocks and deduct from balance in users account
- sum_req = round(price * quantity,2)
- balance = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
- balance = round(balance[0]['cash'])
- remaining = balance - sum_req
- if balance < sum_req:
- return apology("You do not have sufficient funds for this transaction, please try again")
- else:
- #insert transaction into 'transactions' table
- db.execute ("UPDATE users SET cash = :cash WHERE id = :id", cash = remaining, id = session["user_id"])
- db.execute ("INSERT INTO 'transactions' (users_id, symbol, number, price, date, total_cost) VALUES (user, symbol, quantity, price, datetime('now'), total)")
- #check if stock is already in the 'portfolio' table
- existing_symbol = db.execute ("SELECT symbol = :symbol, number = :number FROM 'users' WHERE users_id = :id", symbol = symbol, number = number, id = user)
- #if so add new stock to existing quantity
- if existing_symbol:
- db.execute ("UPDATE 'portfolio' SET number = number + :quantity, current_value = :new_value where id = :id", quantity=quantity, new_value = (number +quantity)*price, id=user)
- #if not insert new record
- else:
- db.execute ("INSERT INTO 'portfolio' (users_id, symbol, number, current_value) VALUES (users_id, symbol, number, current_values)")
- #placeholder for now
- return render_template("success.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement