def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def index(): """Show portfolio of stocks""" DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) TOTAL_SUM = DBcash[0]['cash'] DBcash[0]['cash'] = usd(DBcash[0]['cash']) M = sumStocks(session["user_id"]) for stock in M: M[stock]['symbol'] = stock stock_info = lookup(M[stock]['symbol']) if not stock_info: apology("Database does not have contact with site for fetching prices") M[stock].update(stock_info) M[stock]['curr_total'] = M[stock]['price'] * M[stock]['amount'] M[stock]['price'] = usd( M[stock]["price"] ) TOTAL_SUM += M[stock]['total'] M[stock]['curr_total'] = usd( M[stock]['curr_total'] ) TOTAL_SUM = usd(TOTAL_SUM) N = {} for stock in M: if M[stock]['amount'] > 0: #print(f"M[stock]['symbol'] = {M[stock]['symbol']}") #print(f"M[stock] = {M[stock]}") N[M[stock]['symbol']] = M[stock] return render_template("index.html",DBcash=DBcash,DBstocks=N,TOTAL_SUM=TOTAL_SUM)
def account(): """Allow user to delete their account""" if request.method == "POST": # Ensure password was submitted if not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE id = :userID", userID=session["user_id"]) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # delete from users resultAccountDeleteU = db.execute( "DELETE FROM users WHERE id = :sessionid", sessionid=session["user_id"]) if not resultAccountDeleteU: return apology("Failed to delete account for whatever reason") # delete from history resultAccountDeleteH = db.execute( "DELETE FROM history WHERE userID = :sessionid", sessionid=session["user_id"]) if not resultAccountDeleteH: return apology("Failed to delete account for whatever reason") # delete from portfolios resultAccountDeleteP = db.execute( "DELETE FROM portfolios WHERE userID = :sessionid", sessionid=session["user_id"]) if not resultAccountDeleteP: return apology("Failed to delete account for whatever reason") session.clear() return redirect("/") else: return render_template("account.html")
def register(): """Register user""" # clear session session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": username = request.form.get("username") password = request.form.get("password") confirmation = request.form.get("confirmation") # check form is correctly entered if not username: return apology("must create a username") if not password: return apology("must create a password") if not confirmation: return apology("must enter password again to confirm") if not password == confirmation: return apology("password and password confirmation must be identical") # encrypt and add result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hashedpassword)", username=username, hashedpassword=generate_password_hash(password)) if not result: return apology("that username is already taken") session["user_id"] = username return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("register.html")
def quote(): """Get stock quote.""" if request.method == "POST": value = request.form.get("symbol") if not value: return apology("Please enter a valid ticker") quote = lookup(value) if not quote: return apology("Not a valid symbol") return render_template("display.html", ticker=quote["symbol"], price=usd(int(quote["price"]))) else: return render_template("quote.html")
def quote(): """Get stock quote.""" if request.method == "POST": if not request.form.get("symbol"): return apology("No stock name submitted.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) stock_info["price"] = usd( stock_info["price"] ) return render_template("showQuote.html",stock_info=stock_info) else: return render_template("quote.html")
def index(): """Show portfolio of stocks""" # jinja values = stocks[[symbol, shares, price, value]], cash, totalvalue portfolio = db.execute( "SELECT * FROM portfolios WHERE userID = :sessionid", sessionid=session["user_id"]) cashrow = db.execute( "SELECT cash FROM users WHERE id = :sessionid", sessionid=session["user_id"]) if cashrow: cash = cashrow[0]["cash"] else: cash = 10000 stocks = [] totalvalue = cash if portfolio: for stock in portfolio: symbol = stock["symbol"] shares = stock["shares"] # lookup name and price myvalue = lookup(symbol) if not myvalue: return apology("API not working") price = myvalue["price"] value = int(shares) * float(price) stocks.append({ "symbol": symbol, "shares": shares, "price": usd(price), "value": usd(value) }) totalvalue += price * shares return render_template("index.html", stocks=stocks, cash=usd(cash), totalvalue=usd(totalvalue))
def sell(): """Sell shares of stock""" if request.method == "POST": # form names = symbol, shares symbol = request.form.get("symbol") shares = request.form.get("shares") if not RepresentsInt(shares): return apology("You must enter a valid whole number of shares") if not symbol or not shares or int(shares) <= 0: return apology("You must enter a valid symbol and shares") quote = lookup(symbol) if not quote: return apology("Not a valid symbol, or API not working") price = quote["price"] cost = float(price) * int(shares) # look for in and then update portfolios resultPortfoliosSearch = db.execute( "SELECT shares FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=int(session["user_id"]), symbol=symbol) if int(resultPortfoliosSearch[0]["shares"]) > int(shares): # if you have it and you have extra shares, update it resultPortfoliosUpdate = db.execute("UPDATE portfolios SET shares = shares - :shares WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol, shares=int(shares)) if not resultPortfoliosUpdate: return apology("You don't have enough shares of that stock") elif resultPortfoliosSearch and resultPortfoliosSearch[0]["shares"] == int(shares): # if you have it and you have exactly the same number of shares, just delete it from portfolio resultPortfoliosUpdate = db.execute( "DELETE FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol) if not resultPortfoliosUpdate: return apology("You don't own any shares of that stock") else: return apology("You don't have enough shares of that stock") # also insert it into history table resultHistory = db.execute("INSERT INTO history (userID, shares, symbol, price) VALUES(:userID, :shares, :symbol, :price)", userID=session["user_id"], shares=0 - int(shares), symbol=symbol, price=float(price)) if not resultHistory: return apology("Problem making a purchase. Please try again later.") # and update users table cash resultUsers = db.execute( "UPDATE users SET cash = cash + :cost WHERE id = :sessionid", cost=cost, sessionid=session["user_id"]) if not resultUsers: return apology("Problem updating your wallet. Please try again later.") # redirect to index return redirect("/") else: # get symbols resultSymbols = db.execute( "SELECT symbol FROM portfolios WHERE userID = :sessionid", sessionid=session["user_id"]) if not resultSymbols: return apology("You don't have any stocks to sell") return render_template("sell.html", symbols=resultSymbols)
def buy(): """Buy shares of stock""" if request.method == "POST": if not request.form.get("symbol"): return apology("No stock name submitted.",400) if not request.form.get("shares"): return apology("No stock amount submitted.",400) try: a = int(request.form.get("shares")) except: return apology("invalid amount of shares.",400) if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: return apology("invalid amount of shares.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) tot_price = stock_info["price"] * int(request.form.get("shares")) if int(DBcash[0]['cash']) > tot_price: result = db.execute("INSERT INTO transactions (symbol,price,amount,date,Uid) VALUES(:symbol,:price,:amount, :date,:Uid)", symbol=stock_info["symbol"], price=stock_info["price"], amount=request.form.get("shares"), date=datetime.now(), Uid=session["user_id"] ) if not result: return apology("The transaction could not be completed.") else: db.execute("UPDATE users SET cash = cash - :tot_price where id = :Uid", tot_price = tot_price, Uid = session["user_id"]) else: return apology("Insufficient funds.") return redirect("/") else: return render_template("buy.html",symbol={"symbol":"Stock symbol"})
def buy(): """Buy shares of stock""" if request.method == "POST": # form names = symbol, shares symbol = request.form.get("symbol") shares = request.form.get("shares") if not RepresentsInt(shares): return apology("You must enter a valid number of shares") if not symbol or not shares or int(shares) <= 0: return apology("You must enter a valid symbol and shares") quote = lookup(symbol) if not quote: return apology("Not a valid symbol or API not working") walletrow = db.execute( "SELECT * FROM users WHERE id = :sessionid", sessionid=session["user_id"]) wallet = walletrow[0]["cash"] price = quote["price"] cost = float(price) * int(shares) if wallet < cost: return apology("Not enough cash in account") # if you can afford it, insert into history table resultHistory = db.execute("INSERT INTO history (userID, shares, symbol, price) VALUES(:userID, :shares, :symbol, :price)", userID=session["user_id"], shares=int(shares), symbol=symbol, price=float(price)) if not resultHistory: return apology("Problem making a purchase. Please try again later.") # look for in and then update portfolios resultPortfoliosSearch = db.execute( "SELECT shares FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=int(session["user_id"]), symbol=symbol) if resultPortfoliosSearch: # if you found it, update it resultPortfoliosUpdate = db.execute( "UPDATE portfolios SET shares = shares + :shares WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol, shares=shares) if not resultPortfoliosUpdate: return apology("Error resultPortfoliosUpdate") else: resultPortfoliosAdd = db.execute("INSERT INTO portfolios (userID, shares, symbol) VALUES(:userID, :shares, :symbol)", userID=session["user_id"], shares=int(shares), symbol=symbol ) if not resultPortfoliosAdd: return apology("Error resultPortfoliosAdd") # and update users table cash resultUsers = db.execute( "UPDATE users SET cash = cash - :cost WHERE id = :sessionid", cost=cost, sessionid=session["user_id"]) if not resultUsers: return apology("Problem updating your wallet. Please try again later.") # redirect to index return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) TOTAL_SUM = DBcash[0]['cash'] DBcash[0]['cash'] = usd(DBcash[0]['cash']) M = sumStocks(session["user_id"]) N = {} #print(M) for stock in M: if M[stock]['amount'] > 0: N[stock] = M[stock] #print(N) if request.method == "POST": #print("Sell Post") if not request.form.get("symbol"): return apology("No stock name submitted.",400) if not request.form.get("shares"): return apology("No stock amount submitted.",400) try: a = int(request.form.get("shares")) except: return apology("invalid amount of shares.",400) #if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: return apology("invalid amount of shares.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) if request.form.get("symbol") in M: if M[request.form.get("symbol")]['amount'] >= int(request.form.get("shares")): tot_price = stock_info["price"] * int(request.form.get("shares")) result = db.execute("INSERT INTO transactions (symbol,price,amount,date,Uid) VALUES(:symbol,:price,:amount, :date,:Uid)", symbol=stock_info["symbol"], price=stock_info["price"], amount=-int(request.form.get("shares")), date=datetime.now(), Uid=session["user_id"] ) if not result: return apology("The transaction could not be completed.") else: db.execute("UPDATE users SET cash = cash + :tot_price where id = :Uid", tot_price = tot_price, Uid = session["user_id"]) else: return apology("Not enuff shares to sell.",400) # TODO: write code... return redirect("/") #return render_template("sell.html",DBstocks=M) else: #print("Sell else") return render_template("sell.html",DBstocks=N)
def register(): """Register user""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 400) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 400) elif not request.form.get("confirmation"): return apology("must provide password twice!", 400) elif request.form.get("password") != request.form.get("confirmation"): return apology("Password and confirmation is not equal", 400) PWhash = generate_password_hash(request.form.get("password")) #PWhash = pwd_context.encrypt() result = db.execute( "INSERT INTO users (username,hash) VALUES(:username, :PWhash)", username=request.form.get("username"),PWhash=PWhash ) if not result: return apology("Username already excists",400) #return render_template("registerOK.html",username=request.form.get("Rusername")) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("register.html")
def quote(): """Get stock quote.""" return apology("TODO")
def sell(): """Sell shares of stock""" # User reached route via POST (as by clicking the Sell button) if request.method == "POST": # Ensure a stock symbol was submitted if not request.form.get("symbol"): return apology("must provide a stock symbol", 400) # Ensure # of shares was submitted elif not request.form.get("shares"): return apology("must provide # of shares", 400) # Select the SUM of shares owned of input stock owned_shares = db.execute( "SELECT SUM(shares) FROM transactions WHERE symbol = :symbol AND user_id = :userid", symbol=request.form.get("symbol"), userid=session["user_id"]) owned_shares = int(owned_shares[0]["SUM(shares)"]) # Convert input # of shares to an integer try: sold_shares = int(request.form.get("shares")) except: return apology("# of shares must be a positive integer", 400) # Ensure that user owns shares of input stock if owned_shares < 1: return apology("you don't own any of these shares", 400) # Ensure user is trying to sell a positive integer of share elif sold_shares < 1: return apology("# of shares must be a positive integer", 400) # Ensure user owns at least the number of shares they are selling elif owned_shares < sold_shares: return apology("you can not sell more shares than you own", 400) stock = lookup(request.form.get("symbol")) minus_shares = -sold_shares amount = stock["price"] * minus_shares # Add sell order to transactions table db.execute( "INSERT INTO transactions (user_id, symbol, shares, amount) VALUES (:userid, :symbol, :shares, :amount)", userid=session["user_id"], symbol=stock["symbol"], shares=minus_shares, amount=amount) # Update available cash on users table cash = db.execute("SELECT cash FROM users WHERE id = :userid", userid=session["user_id"]) cash = float(cash[0]["cash"]) db.execute("UPDATE users SET cash = :cash WHERE id = :userid", cash=(cash - amount), userid=session["user_id"]) return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: # Select a user's stocks stocks = db.execute( "SELECT symbol FROM transactions GROUP BY symbol HAVING user_id = :userid AND SUM(shares) > 0 ORDER BY symbol", userid=session["user_id"]) return render_template("sell.html", stocks=stocks)
def errorhandler(e): """Handle error""" return apology(e.name, e.code)
def settings(): """Allows user to change information""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": id = session["user_id"] if request.form.get("username"): username = request.form.get("username") # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) if rows == None: return apology("Username is taken :(", 400) else: db.execute( "UPDATE users SET username=:username WHERE userid = :id", username=username, id=id) if request.form.get("fname"): db.execute("UPDATE users SET name=:fname WHERE userid = :id", fname=request.form.get("fname"), id=id) if request.form.get("surname"): db.execute("UPDATE users SET surname=:surname WHERE userid = :id", surname=request.form.get("surname"), id=id) if request.form.get("email"): db.execute("UPDATE users SET email=:email WHERE userid = :id", email=request.form.get("email"), id=id) if request.form.get("phone"): phone = request.form.get("phone") if phonec(phone) == "fail": return apology("Must enter valid 10 digit phone number", 400) phone = phonec(request.form.get("phone")) db.execute("UPDATE users SET phone=:phone WHERE userid = :id", phone=phone, id=id) # checks if user entered passwords if request.form.get("oldpass"): if not request.form.get("newpass"): return apology("must enter new password", 400) elif not request.form.get("verification"): return apology("must verify password", 400) else: # stores passwords oldpass = request.form.get("oldpass") newpass = request.form.get("newpass") verification = request.form.get("verification") row = db.execute( "SELECT password FROM users WHERE userid = :id", id=id) # ensure user inputs valid information if not check_password_hash(row[0]["password"], oldpass): return apology("old password is incorrect", 400) if newpass != verification: return apology("new passwords must match", 400) # update password newpass = generate_password_hash(newpass) db.execute( "UPDATE users SET password=:newpass WHERE userid = :id", newpass=newpass, id=id) return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: id = session["user_id"] # gets user information user = db.execute("SELECT * FROM users WHERE userid=:userid", userid=id)[0] email = user["email"] fname = user["name"] sname = user["surname"] phone = user["phone"] username = user["username"] return render_template("settings.html", username=username, fname=fname, sname=sname, email=email, phone=phone)
def register(): """Register user""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": username = request.form.get("username") name = request.form.get("name") surname = request.form.get("surname") email = request.form.get("email") phone = request.form.get("phone") # Ensure username was submitted if not username: return apology("must provide username", 400) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 400) # Ensure passwords match elif request.form.get("password") != request.form.get("confirmation"): return apology("Passwords must match", 400) # Ensure name was submitted elif not request.form.get("name"): return apology("Must enter first name", 400) # Ensure surname was submitted elif not request.form.get("surname"): return apology("Must enter last name", 400) # Ensure email was submitted elif not request.form.get("email"): return apology("Must enter email", 400) # Ensure phone number was submitted elif not request.form.get("phone"): return apology("Must enter phone number", 400) # checks if valid phone number if phonec(phone) == "fail": return apology("Must enter valid 10 digit phone number", 400) phone = phonec(phone) # hashes password hash = generate_password_hash(request.form.get("password")) # inserts new user in data base and checks username rows = db.execute( "INSERT INTO users ( username, password, name, surname, email, phone ) VALUES( :username, :hash, :name, :surname, :email, :phone )", username=username, hash=hash, name=name, surname=surname, email=email, phone=phone) if rows == None: return apology("Username is taken :(", 400) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) # Remember which user has logged in session["user_id"] = rows[0]["userid"] return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("register.html")
def buy(): """Buy shares of stock""" if request.method == "GET": return render_template("buy.html") else: symbol = request.form.get("symbol") shares = request.form.get("shares") try: shares = int(shares) except ValueError: return apology("Invalid quantity requested") else: if symbol == None: return apology("Unrecognized stock symbol") elif shares < 0: return apology("No refunds. Negative value entered") else: stock = lookup(symbol) if lookup(symbol) == None: return apology("Stock symbol not found") # calculate total stock cost cost = shares * lookup(symbol)["price"] # check cash in user's wallet cash = db.execute("SELECT cash FROM users WHERE \ id=:user_id;", user_id=session["user_id"]) # calculate balance after purchase balance = cash[0]["cash"] - cost if balance < 0: return apology("Insufficient funds.") else: # update history of transactions db.execute("INSERT INTO transactions (symbol, shares, price, id) \ VALUES(:symbol, :shares, :price, :user_id)", \ symbol=stock["symbol"], shares=shares, \ price=usd(stock["price"]), user_id=session["user_id"]) # update cash in users db.execute("UPDATE users SET cash = cash - :purchase WHERE id=:user_id", \ user_id=session["user_id"], purchase=stock["price"] * shares) # calculate number of shares owned owned = db.execute("SELECT shares, total FROM portfolio WHERE id=:user_id \ AND symbol=:symbol", user_id=session["user_id"], \ symbol=stock["symbol"]) if owned: # update shares in portfolio total_shares = owned[0]["shares"] + shares total_dec = Decimal(owned[0]["total"].strip('$')) total_value = float(total_dec) + cost db.execute("UPDATE portfolio SET shares=:shares, total=:total \ WHERE id=:user_id AND symbol=:symbol", \ shares=total_shares, total=total_value, \ user_id=session["user_id"], symbol=stock["symbol"]) else: # add portfolio record of stock db.execute("INSERT INTO portfolio (name, shares, price, total, symbol, id) \ VALUES(:name, :shares, :price, :total, :symbol, :user_id)", \ name=stock["name"], shares=shares, price=usd(stock["price"]), \ total=usd(shares * stock["price"]), symbol=stock["symbol"], \ user_id=session["user_id"]) # Redirect user to home page return redirect("/")
def vote(): # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure name was submitted if not request.form.get("name"): return apology("must provide name", 403) elif not request.form.get("email"): return apology("must provide email", 403) elif not request.form.get("aadhaar"): return apology("must provide aadhaar card no.", 403) elif not request.form.get("phone"): return apology("must provide phone no.", 403) elif not request.form.get("pid"): return apology("must provide party id", 403) with sql.connect("data.db") as db: data = db.cursor() name = request.form.get("name") aadhaar = int(request.form.get("aadhaar")) phone = request.form.get("phone") pid = request.form.get("pid") email = request.form.get("email") ak = session["user_id"] if session["type"] == 1: data.execute("SELECT aadhaar FROM candidate WHERE email = ?", (email,)) rows = data.fetchall() aad = rows[0][0] if aad == aadhaar: data.execute("UPDATE candidate SET voted = ? WHERE email = ?", (1, email,)) data.execute("SELECT count FROM candidate WHERE c_id = ?", (pid,)) rows = data.fetchall() current_vote = rows[0][0] current_vote += 1 data.execute("UPDATE candidate SET count = ? WHERE c_id = ?", (current_vote, pid,)) else: return apology("DETAILS ARE NOT MATCHING OUR RECORD",403) elif session["type"] == 0: data.execute("SELECT aadhaar FROM users WHERE email = ?", (email,)) rows = data.fetchall() aad = rows[0][0] if aad == aadhaar: data.execute("UPDATE users SET voted = ? WHERE email = ?", (1, email,)) data.execute("SELECT count FROM candidate WHERE c_id = ?", (pid,)) rows = data.fetchall() current_vote = rows[0][0] current_vote += 1 data.execute("UPDATE candidate SET count = ? WHERE c_id = ?", (current_vote, pid,)) else: return apology("DETAILS ARE NOT MATCHING OUR RECORD",403) else: return apology("INTERNAL SERVER ERROR", 403) return redirect("/main") # User reached route via GET (as by clicking a link or via redirect) else: with sql.connect("data.db") as db: data = db.cursor() ak = session["user_id"] if session["type"] == 1: data.execute("SELECT voted FROM candidate WHERE c_id = ?", (ak,)) voted = data.fetchall() if voted[0][0] == 0: data.execute("SELECT c_id, party, name, symbol FROM candidate") rows = data.fetchall() return render_template('stats/vote.html',details = rows) else: return redirect("/main") elif session["type"] == 0: data.execute("SELECT voted FROM users WHERE id = ?", (ak,)) voted = data.fetchall() if voted[0][0] == 0: data.execute("SELECT c_id, party, name, symbol FROM candidate") rows = data.fetchall() return render_template('stats/vote.html',details = rows) else: return redirect("/main") else: return apology("INTERNAL SERVER ERROR", 403)
def cregister(): """Register Candidate""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("name"): return apology("must provide FIRST NAME", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) elif not request.form.get("confirmation"): return apology("must provide password again", 403) elif request.form.get("password") != request.form.get("confirmation"): return apology("passwords should match", 403) elif not request.form.get("email"): return apology("MUST PROVIDE EMAIL", 403) elif not request.form.get("phone"): return apology("MUST PROVIDE PHONE NO.", 403) elif not request.form.get("aadhaar"): return apology("MUST PROVIDE AADHAAR CARD NO.", 403) elif not request.form.get("country"): return apology("MUST PROVIDE COUNTRY NAME", 403) elif not request.form.get("zip"): return apology("MUST PROVIDE PINCODE", 403) elif not request.form.get("pname"): return apology("MUST PROVIDE PARTY NAME", 403) elif not request.form.get("symbol"): return apology("MUST PROVIDE Party Symbol", 403) # Query database for username with sql.connect("data.db") as db: data = db.cursor() aadhaar=request.form.get("aadhaar") phone=request.form.get("phone") email = request.form.get("email") password = request.form.get("password") zip = request.form.get("zip") name = request.form.get("name") symbol = request.form.get("symbol") hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8) party = request.form.get("pname") country = request.form.get("country") data.execute("SELECT * FROM candidate WHERE email = ?", (email,)) rows = data.fetchall() if len(rows) != 0: return render_template("stats/register.html", error=1, issue="E-mail ID") data.execute("SELECT * FROM candidate WHERE phone = ?", (phone,)) rows = data.fetchall() if len(rows) != 0: return render_template("stats/register.html", error=1, issue="Phone No.") data.execute("SELECT * FROM candidate WHERE aadhaar = ?",(aadhaar,)) rows = data.fetchall() if len(rows) != 0: return render_template("stats/candidate-register.html", error=1, issue="Aadhaar card No.") data.execute("INSERT INTO candidate (name, email, hash, phone, aadhaar, country, zip, party, symbol) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (name, email, hash, phone, aadhaar, country, zip, party, symbol)) db.commit() # Redirect user to home page return redirect("/candidate-login") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("stats/cregister.html") return apology("INTERNAL SERVER ERROR", 404)
def analysis_search(): if request.method == "POST": name = request.form.get("player_name") if (not name): return apology("No player name", 403) player = db.execute( "SELECT * FROM ':i - Player Database' WHERE Name = :n", i=session["user_id"], n=name) if len(player) != 1: return apology("Player does not exist", 403) elif len(player) > 1: return apology("Please enter unique name", 403) else: information = [ player[0]["Name"], player[0]["Rating"], player[0]["Consistency"], player[0]["Games Played"] ] information[1] = round(information[1], 1) information[1] = format(information[1], '.1f') information[2] = round(information[2], 2) information[2] = format(information[2], '.2f') month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] counter = 1 dates = ['N/A', 'N/A', 'N/A', 'N/A'] results = [0, 0, 0] progress = [] avg_opp_rating = [0, 0, 0] extra_info = [1200.0, 1200.0, 0, 'N/A'] date = datetime.now() date = date.strftime("%Y-%m-%d") today = datetime.now() today = today.strftime("%Y-%m-%d") if int(date[5:7]) != 1: date = date[:5] + str(int(date[5:7]) - 1).zfill(2) + date[7:] else: date = str(int(date[:4]) - 1) + str(-12) + date[7:] while True: games = db.execute( "SELECT * FROM ':i - Result History' WHERE ID = :c", i=session["user_id"], c=counter) if len(games) != 1: break if games[0]["Player_A"] != name and games[0][ "Player_B"] != name: counter += 1 continue else: if dates[0] == 'N/A': dates[0] = games[0]["Timestamp"] dates[0] = dates[0][:10] if games[0]["Player_A"] == name and float( games[0]["Result"]) == 1.0: results[0] += 1 avg_opp_rating[0] += games[0]["B_New_Rating"] - games[ 0]["B_Change"] if extra_info[2] <= games[0]["B_New_Rating"] - games[ 0]["B_Change"]: extra_info[2] = games[0]["B_New_Rating"] - games[ 0]["B_Change"] extra_info[3] = games[0]["Player_B"] dates[3] = games[0]["Timestamp"] dates[3] = dates[3][:10] if games[0]["Player_B"] == name and float( games[0]["Result"]) == 0.0: results[0] += 1 avg_opp_rating[0] += games[0]["A_New_Rating"] - games[ 0]["A_Change"] if extra_info[2] <= games[0]["A_New_Rating"] - games[ 0]["A_Change"]: extra_info[2] = games[0]["A_New_Rating"] - games[ 0]["A_Change"] extra_info[3] = games[0]["Player_A"] dates[3] = games[0]["Timestamp"] dates[3] = dates[3][:10] elif games[0]["Player_A"] == name and float( games[0]["Result"]) == 0.0: results[1] += 1 avg_opp_rating[1] += games[0]["B_New_Rating"] - games[ 0]["B_Change"] elif games[0]["Player_B"] == name and float( games[0]["Result"]) == 1.0: results[1] += 1 avg_opp_rating[1] += games[0]["A_New_Rating"] - games[ 0]["A_Change"] elif games[0]["Player_A"] == name and float( games[0]["Result"]) == 0.5: results[2] += 1 avg_opp_rating[2] += games[0]["B_New_Rating"] - games[ 0]["B_Change"] elif games[0]["Player_B"] == name and float( games[0]["Result"]) == 0.5: results[2] += 1 avg_opp_rating[2] += games[0]["A_New_Rating"] - games[ 0]["A_Change"] if games[0]["Player_A"] == name: if games[0]["Timestamp"][0:4] > date[0:4] or ( games[0]["Timestamp"][0:4] == date[0:4] and games[0]["Timestamp"][5:7] > date[5:7] ) or (games[0]["Timestamp"][0:4] == date[0:4] and games[0]["Timestamp"][5:7] == date[5:7] and games[0]["Timestamp"][8:] > date[8:]): if today[5:7] == games[0]["Timestamp"][5:7]: progress.append([ games[0]["A_New_Rating"], games[0]["A_Consistency"], int(today[8:]) - int(games[0]["Timestamp"][8:10]) ]) else: progress.append([ games[0]["A_New_Rating"], games[0]["A_Consistency"], int(today[8:]) + month[int(games[0]["Timestamp"][5:7]) - 1] - int(games[0]["Timestamp"][8:10]) ]) if len(progress) > 1 and progress[-1][ 2] == progress[-2][2]: del progress[-2] if games[0]["A_New_Rating"] >= extra_info[0]: extra_info[0] = games[0]["A_New_Rating"] dates[1] = games[0]["Timestamp"] dates[1] = dates[1][:10] if games[0]["A_New_Rating"] <= extra_info[1]: extra_info[1] = games[0]["A_New_Rating"] dates[2] = games[0]["Timestamp"] dates[2] = dates[2][:10] else: if games[0]["Timestamp"][0:4] > date[0:4] or ( games[0]["Timestamp"][0:4] == date[0:4] and games[0]["Timestamp"][5:7] > date[5:7] ) or (games[0]["Timestamp"][0:4] == date[0:4] and games[0]["Timestamp"][5:7] == date[5:7] and games[0]["Timestamp"][8:] > date[8:]): if today[5:7] == games[0]["Timestamp"][5:7]: progress.append([ games[0]["B_New_Rating"], games[0]["B_Consistency"], int(today[8:]) - int(games[0]["Timestamp"][8:10]) ]) else: progress.append([ games[0]["B_New_Rating"], games[0]["B_Consistency"], int(today[8:]) + month[int(games[0]["Timestamp"][5:7]) - 1] - int(games[0]["Timestamp"][8:10]) ]) if len(progress) > 1 and progress[-1][ 2] == progress[-2][2]: del progress[-2] if games[0]["B_New_Rating"] >= extra_info[0]: extra_info[0] = games[0]["B_New_Rating"] dates[1] = games[0]["Timestamp"] dates[1] = dates[1][:10] if games[0]["B_New_Rating"] <= extra_info[1]: extra_info[1] = games[0]["B_New_Rating"] dates[2] = games[0]["Timestamp"] dates[2] = dates[2][:10] counter += 1 counter = 1 c_rank = 1 r_rank = 1 gp_rank = 1 number = db.execute("SELECT COUNT(*) FROM ':i - Player Database'", i=session["user_id"]) number = int(number[0]["COUNT(*)"]) total = number while number != 1: row = db.execute( "SELECT * FROM ':i - Player Database' WHERE ID = :c", i=session["user_id"], c=counter) if len(row) != 1 or row[0]["Name"] == name: counter += 1 continue print(row[0]) if row[0]["Rating"] > float(information[1]): r_rank += 1 if row[0]["Consistency"] > float(information[2]): c_rank += 1 if row[0]["Games Played"] > float(information[3]): gp_rank += 1 counter += 1 number -= 1 counter = total rank = [r_rank, c_rank, gp_rank] percentile = [ round(100 * (counter - rank[i]) / counter) for i in range(len(rank)) ] avg_opp_rating.append(avg_opp_rating[0] + avg_opp_rating[1] + avg_opp_rating[2]) for i in range(len(extra_info) - 1): extra_info[i] = round(extra_info[i], 1) if extra_info[2] == 0: extra_info[2] = 'N/A' results.append(results[0] + results[1] + results[2]) for i in range(len(avg_opp_rating)): if avg_opp_rating[i] == 0: avg_opp_rating[i] = 'N/A' else: avg_opp_rating[i] = round(avg_opp_rating[i] / results[i], 1) return render_template("analysis.html", date=date, information=information, rank=rank, percentile=percentile, dates=dates, progress=progress, results=results, avg_opp_rating=avg_opp_rating, extra_info=extra_info, counter=counter) else: return render_template("analysis_search.html")
def prediction(): if request.method == "POST": if (not request.form.get("a")) or (not request.form.get("b")): return apology("Need players", 403) name_one = request.form.get("a") name_two = request.form.get("b") info = db.execute( "SELECT * FROM ':i - Player Database' WHERE NAME = :n", i=session["user_id"], n=name_one) if len(info) != 1: return apology("Player one does not exist", 403) player_one = [ name_one, info[0]["Rating"], info[0]["Games Played"], info[0]["Consistency"] ] info = db.execute( "SELECT * FROM ':i - Player Database' WHERE NAME = :n", i=session["user_id"], n=name_two) if len(info) != 1: return apology("Player two does not exist", 403) player_two = [ name_two, info[0]["Rating"], info[0]["Games Played"], info[0]["Consistency"] ] player_one[1] = round(player_one[1], 1) player_one[1] = format(player_one[1], '.1f') player_one[2] = round(player_one[2], 2) player_one[2] = format(player_one[2], '.2f') player_two[1] = round(player_two[1], 1) player_two[1] = format(player_two[1], '.1f') player_two[2] = round(player_two[2], 2) player_two[2] = format(player_two[2], '.2f') probabilities = [] probabilities.append( standard_probability(float(player_one[1]), float(player_two[1]))) probabilities.append( standard_probability(float(player_two[1]), float(player_one[1]))) print(probabilities) probabilities[0] = round(probabilities[0] * 100, 1) probabilities[0] = format(probabilities[0], '.1f') probabilities[1] = round(probabilities[1] * 100, 1) probabilities[1] = format(probabilities[1], '.1f') history_table = [] counter = 1 total = 0 while True: row = db.execute( "SELECT * FROM ':i - Result History' WHERE ID = :c", i=session["user_id"], c=counter) if len(row) != 1: break if not ((row[0]["Player_A"] == name_one and row[0]["Player_B"] == name_two) or (row[0]["Player_A"] == name_two and row[0]["Player_B"] == name_one)): counter += 1 continue else: row[0]['A_Change'] = round(row[0]['A_Change'], 1) row[0]['A_Change'] = format(row[0]['A_Change'], '.1f') row[0]['A_New_Rating'] = round(row[0]['A_New_Rating'], 1) row[0]['A_New_Rating'] = format(row[0]['A_New_Rating'], '.1f') row[0]['A_Consistency'] = round(row[0]['A_Consistency'], 2) row[0]['A_Consistency'] = format(row[0]['A_Consistency'], '.2f') row[0]['B_Change'] = round(row[0]['B_Change'], 1) row[0]['B_Change'] = format(row[0]['B_Change'], '.1f') row[0]['B_New_Rating'] = round(row[0]['B_New_Rating'], 1) row[0]['B_New_Rating'] = format(row[0]['B_New_Rating'], '.1f') row[0]['B_Consistency'] = round(row[0]['B_Consistency'], 2) row[0]['B_Consistency'] = format(row[0]['B_Consistency'], '.2f') history_table.append([ row[0]['Player_A'], row[0]['A_Change'], row[0]['A_New_Rating'], row[0]['A_Consistency'], row[0]['Player_B'], row[0]['B_Change'], row[0]['B_New_Rating'], row[0]['B_Consistency'], row[0]['Result'], row[0]['Timestamp'] ]) counter += 1 total += 1 counter -= 1 history_table.reverse() return render_template("predicresults.html", probabilities=probabilities, history_table=history_table, total=total, player_one=player_one, player_two=player_two) else: return render_template("prediction.html")
def result(): if request.method == "POST": if (not request.form.get("a")) or (not request.form.get("b")) or ( not request.form.get("result")): return apology("Need players and result", 403) name_one = request.form.get("a") name_two = request.form.get("b") result = request.form.get("result") info = db.execute( "SELECT * FROM ':i - Player Database' WHERE NAME = :n", i=session["user_id"], n=name_one) if len(info) != 1: return apology("Player one does not exist", 403) player_one = [ info[0]["Rating"], info[0]["Games Played"], info[0]["Consistency"] ] games_one = info[0]["Games Played"] info = db.execute( "SELECT * FROM ':i - Player Database' WHERE NAME = :n", i=session["user_id"], n=name_two) if len(info) != 1: return apology("Player two does not exist", 403) player_two = [ info[0]["Rating"], info[0]["Games Played"], info[0]["Consistency"] ] updated = New_Elo(player_one, player_two, result) db.execute( "UPDATE ':i - Player Database' SET Rating = :r WHERE NAME = :n", i=session["user_id"], n=name_one, r=updated[0]) db.execute( "UPDATE ':i - Player Database' SET Consistency = :r WHERE NAME = :n", i=session["user_id"], n=name_one, r=updated[1]) db.execute( "UPDATE ':i - Player Database' SET Rating = :r WHERE NAME = :n", i=session["user_id"], n=name_two, r=updated[2]) db.execute( "UPDATE ':i - Player Database' SET Consistency = :r WHERE NAME = :n", i=session["user_id"], n=name_two, r=updated[3]) db.execute( "UPDATE ':i - Player Database' SET 'Games Played' = :g WHERE NAME = :n", i=session["user_id"], n=name_one, g=games_one + 1) db.execute( "UPDATE ':i - Player Database' SET 'Games Played' = :g WHERE NAME = :n", i=session["user_id"], n=name_two, g=info[0]["Games Played"] + 1) db.execute( "INSERT INTO ':i - Result History' ('Player_A', 'A_Change', 'A_New_Rating', 'A_Consistency', 'Player_B', 'B_Change', 'B_New_Rating', 'B_Consistency', 'Result') VALUES (:n1, :c1, :r1, :co1, :n2, :c2, :r2, :co2, :r)", i=session["user_id"], n1=name_one, n2=name_two, r=result, r1=updated[0], c1=updated[0] - player_one[0], r2=updated[2], c2=updated[2] - player_two[0], co1=updated[1], co2=updated[3]) print(updated) flash('Result Added!') return redirect("/") else: return render_template("result.html")
def register(): """Register user""" # Forget any user_id session.clear() if request.method == "POST": """Register user""" username = request.form.get("username") email = request.form.get("email") # Checks if user input a username if not username: return apology("Missing username!", 400) # Checks for valid email and confirmation if not (email or request.form.get("econfirm")): return apology("Missing email!", 400) if not email == request.form.get("econfirm"): return apology("Your emails do not match", 400) if not request.form.get("pnumber"): return apology("Please insert your phone number") # Checks for matching passwords if not (request.form.get("password") or request.form.get("confirmation")): return apology("Missing password", 400) if not (request.form.get("password") == request.form.get("confirmation")): return apology("your passwords do not match", 400) # Checks if user inputs dorm and year if not (request.form.get("dorm") or request.form.get("year")): return apology("Please choose your dorm and year", 400) name = request.form.get("firstname") + " " + request.form.get( "lastname") # Saves user info into database # Checks if username is already taken result = db.execute("SELECT * FROM users WHERE username= :username", username=username) if result: return apology("this username is already taken", 400) # Checks if email is already taken taken = db.execute("SELECT * FROM users WHERE email= :email", email=request.form.get("email")) if taken: return apology("this email is already in use", 400) # Generates a string of 3-9 numbers that serves as a verification code # Is not unique, but would be difficult to guess vcode = "" for x in range(3): vcode += str(random.randint(1, 100) * 3) db.execute( "INSERT INTO users (username, hash, dorm, year, name, email, pnumber, vcode) VALUES (:username, :hashp, :dorm, :year, :name, :email, :pnumber, :vcode)", username=username, hashp=generate_password_hash(request.form.get("password")), dorm=request.form.get("dorm"), year=request.form.get("year"), name=name, email=request.form.get("email"), pnumber=request.form.get("pnumber"), vcode=vcode) # Saves user id into a session session["user_id"] = db.execute( "SELECT id FROM users WHERE username= :username", username=username) # Sends user a verification email msg = "Hello! Thank you for registering for ThriftShare! Click the link below and use this verification code \'{0}\' to verify your account to begin sharing!\nhttp://ide50-juanmolina.cs50.io:8080/verify".format( vcode) # Below code taken from CS50 notes @ https://cs50.harvard.edu/2018/fall/weeks/7/notes/ server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("*****@*****.**", "juanvanessa") server.sendmail("*****@*****.**", request.form.get("email"), msg) server.quit() return redirect("/login") else: return render_template("register.html")
def buy(): """Buy shares of stock""" if request.method == "POST": symbol = lookup(request.form.get("symbol")) if not symbol or symbol == None: return apology("Symbol not found", 403) if not request.form.get("shares"): return apology("Enter number o shares", 403) rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"]) if float(rows[0]["cash"]) < (int(request.form.get("shares")) * float(symbol["price"])): return apology("Not enough cash", 403) else: cash = float(rows[0]["cash"]) - (int(request.form.get("shares")) * float(symbol["price"])) total = int(request.form.get("shares")) * float(symbol["price"]) db.execute("UPDATE users SET cash = :cash WHERE id = :id", cash=cash, id=session["user_id"]) db.execute( "INSERT INTO orders (order_by, share_name, shares_qty, share_price, purchase_total) VALUES (:by, :name, :qty, :price, :total)", by=session["user_id"], name=symbol["symbol"], qty=int(request.form.get("shares")), price=symbol["price"], total=total) # Handles index shares_owned_rows = db.execute( "SELECT owned_by, share_name, shares_qty FROM shares_owned WHERE owned_by = :id", id=session["user_id"]) # Make a list of share_name that are attached to the user share_name_list = [] for row in shares_owned_rows: share_name_list.append(row["share_name"]) if symbol["symbol"] in share_name_list: for row in shares_owned_rows: if row["share_name"] == symbol["symbol"]: new_qty = int(row["shares_qty"] + int(request.form.get("shares"))) db.execute( "UPDATE shares_owned SET shares_qty =:qty , holding =:hold WHERE share_name =:name", qty=new_qty, hold=float(new_qty * float(symbol["price"])), name=symbol["symbol"]) else: db.execute( "INSERT INTO shares_owned (owned_by, share_name, shares_qty, share_price, holding) VALUES (:by, :name, :qty, :price, :hold)", by=session["user_id"], name=symbol["symbol"], qty=int(request.form.get("shares")), price=symbol["price"], hold=total) return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" return apology("TODO")
def sell(): """Sell shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": quote = lookup(request.form.get("symbol")) # Ensure symbol was submitted if quote == None: return apology("must provide symbol", 403) # Ensure number of shares was submitted if not request.form.get("shares"): return apology("must provide a number of shares", 403) # Check if shares was a positive integer try: shares = int(request.form.get("shares")) except: return apology("shares must be a positive integer", 400) # Check if # of shares requested was 0 if shares <= 0: return apology("can't buy less than or 0 shares", 400) current_price = quote["price"] stock_name = quote["name"] symbol = quote["symbol"] stocks = db.execute( "SELECT SUM(shares) FROM transactions WHERE user_id = :user_id AND symbol = :symbol GROUP BY symbol", user_id=session["user_id"], symbol=symbol) user_id = session["user_id"] nb_shares = int(stocks[0]["SUM(shares)"]) rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id) cash_remaining = rows[0]["cash"] if shares > nb_shares: return apology("not enough shares") total_price = shares * current_price # update table in the database and insert transactions db.execute("UPDATE users SET cash = cash + :price WHERE id = :user_id", price=total_price, user_id=session["user_id"]) db.execute( "INSERT INTO transactions (user_id, symbol, shares, price_per_share, stock_name, total_price) VALUES(:user_id, :symbol, :shares, :price, :name, :total_price)", user_id=session["user_id"], symbol=symbol, shares=-shares, price=current_price, name=stock_name, total_price=total_price) flash("Sold!") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: stocks = db.execute( "SELECT symbol FROM transactions WHERE user_id = :user_id GROUP BY symbol HAVING SUM(shares) > 0", user_id=session["user_id"]) return render_template("sell.html", stocks=stocks)
def sell(): """Sell shares of stock""" if request.method == "GET": portfolio = db.execute("SELECT symbol FROM portfolio WHERE \ id=:user_id", user_id=session["user_id"]) return render_template("sell.html", portfolio=portfolio) else: symbol = request.form.get("symbol") shares = int(request.form.get("shares")) if not symbol: return apology("Select symbol") # ensure positive integer input if not shares or shares < 1: return apology("Enter a positive number of shares to sell") # query user portfolio user_stocks = db.execute("SELECT symbol, shares FROM portfolio WHERE \ id=:user_id AND symbol=:symbol", user_id=session["user_id"], \ symbol=symbol) # subtract quantity of shares from currently owned available = int(user_stocks[0]["shares"]) if available < shares: return apology("Insufficient shares") # update remaining shares available -= shares # lookup current value of share shareval = lookup(symbol)["price"] value = shareval * shares # query and update user balance userbal = db.execute("SELECT cash FROM users WHERE id=:user_id", \ user_id=session["user_id"]) balance = userbal[0]["cash"] balance += value # update user portfolio databse db.execute("UPDATE portfolio SET shares=:shares, price=:price, \ total=:balance WHERE id=:user_id AND symbol=:symbol", \ shares=available, price=shareval, balance=balance, \ user_id=session["user_id"], symbol=symbol) # remove stock record if no shares remain if available == 0: db.execute("DELETE FROM portfolio WHERE shares=0") # insert record into transactions database db.execute("INSERT INTO transactions (symbol, shares, price, id) \ VALUES(:symbol, :shares, :price, :user_id)", \ symbol=symbol, shares=shares, price=value, \ user_id=session["user_id"]) # update users database for cash (increase balance) db.execute("UPDATE users SET cash=:balance WHERE id=:user_id", \ user_id=session["user_id"], balance=balance) # Redirect user to home page return redirect("/")
def register(): """Register user""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Lowercase username username = request.form.get("username").lower() # Ensure username was submitted and ≠ users if not request.form.get("username") or username == "users": return apology("must provide new username", 400) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 400) # Ensure confirmation was submitted elif not request.form.get("confirmation"): return apology("must provide password again", 400) # Ensure terms are agreed to elif not request.form.get("terms"): return apology("must agree to Terms & Conditions", 400) # Ensure password = confirmation elif request.form.get("password") != request.form.get("confirmation"): return apology("must provide matching passwords", 400) # Generate hash for password hash = generate_password_hash(request.form.get("password")) # Check to see if username already exists rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) if len(rows) != 0: return apology("username already taken", 400) # Insert new user into database into master users list new_user_id = db.execute( "INSERT INTO users (username, hash, first_name, last_name) VALUES (:username, :hash, :first, :last)", username=username, hash=hash, first=request.form.get("first").title(), last=request.form.get("last").title()) # Query database for userid rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) # Remember which user has logged in session["user_id"] = rows[0]["user_id"] # Forget any user_id session.clear() # Redirect user to login page return redirect("/login") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("register.html")
def update2(): """Update Ride""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": rideid = session["rideid"] # checks if user entered date if request.form.get("date"): date = request.form.get("date") db.execute("UPDATE requests SET date=:new WHERE rideid = :id", new=date, id=rideid) # checks if user entered type if request.form.get("type"): type = request.form.get("type") db.execute("UPDATE requests SET type=:new WHERE rideid = :id", new=type, id=rideid) # gets current etime and type user = db.execute("SELECT * FROM requests WHERE rideid = :id", id=rideid)[0] etime = user["etime"] type = user["type"] # checks if user entered optimal time if request.form.get("otime"): otime = request.form.get("otime") # if the user is changing both if request.form.get("etime") and request.form.get("otime"): etime = request.form.get("etime") otime = request.form.get("otime") # checks times if timecheck(type, otime, etime) == "e": return apology( "Earliest time must be earlier than optimum time", 400) elif timecheck(type, otime, etime) == "l": return apology("Latest time must be later than optimum time", 400) db.execute("UPDATE requests SET otime=:new WHERE rideid = :id", new=otime, id=rideid) # regets data in case of change user = db.execute("SELECT * FROM requests WHERE rideid = :id", id=rideid)[0] otime = user["otime"] # checks if user entered wait time time if request.form.get("etime"): etime = request.form.get("etime") # checks times if timecheck(type, otime, etime) == "e": return apology( "Earliest time must be earlier than optimum time", 400) elif timecheck(type, otime, etime) == "l": return apology("Latest time must be later than optimum time", 400) db.execute("UPDATE requests SET etime=:new WHERE rideid = :id", new=etime, id=rideid) # checks if user entered airport if request.form.get("airport"): airport = request.form.get("airport") db.execute("UPDATE requests SET airport=:new WHERE rideid = :id", new=airport, id=rideid) # checks if user entered number of passengers if request.form.get("number"): number = int(request.form.get("number")) db.execute("UPDATE requests SET number=:new WHERE rideid = :id", new=number, id=rideid) matched = match(rideid) return render_template("ordered.html", matched=matched) # User reached route via GET (as by clicking a link or via redirect) else: id = session["user_id"] rideid = session["rideid"] ride = db.execute("SELECT * FROM requests WHERE rideid = :rideid", rideid=rideid)[0] airport = ride["airport"] date = ride["date"] otime = ride["otime"] etime = ride["etime"] number = ride["number"] type = ride["type"] if type == 0: type = "Departure" else: type = "Arrival" return render_template("update2.html", airport=airport, date=date, otime=otime, etime=etime, number=number, type=type)
def account(): """Account settings""" print(request.form) # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # check to see if request is to change password if request.form['submission'] == "change": # Ensure password was submitted if not request.form.get("password"): return flash("You must provide a password") # Ensure confirmation was submitted elif not request.form.get("confirmation"): return flash("You must provide your password again") # Ensure password = confirmation elif request.form.get("password") != request.form.get( "confirmation"): return flash("Passwords do not match") # Generate hash for password hash = generate_password_hash(request.form.get("password")) # update password in database update = db.execute( "UPDATE users SET hash = :hash WHERE user_id = :id", id=session["user_id"], hash=hash) if update: # Clear session and redirect user to login page session.clear() flash("Your password has been successfully changed!") return redirect("/") else: return apology("Error", 400) # check if attempting to delete account elif request.form['submission'] == "delete": # ensure confirmation box is checked if not request.form.get("deletecheck"): flash( "Check the box below if you would like to delete your account." ) # delete account (remove user from master users and remove usertable) else: # remove user from master users table delete = db.execute("DELETE FROM users WHERE user_id = :user", user=session["user_id"]) # remove all rows that include user in friends friendslist = db.execute( "DELETE FROM friends WHERE friend = :name OR user = :name", name=session["my_name"]) # Forget any user_id session.clear() # Redirect to homepage return redirect("/") # User reached route via GET (as by clicking a link or via redirect) return render_template("change.html")
def order(): """Display and get info from departure form""" if request.method == "POST": id = session["user_id"] type = session["type"] # checks if user entered date if not request.form.get("date"): return apology("must provide date", 400) else: date = request.form.get("date") # checks if user entered optimal time if not request.form.get("otime"): return apology("must provide optimal time", 400) else: otime = request.form.get("otime") # checks if user entered wait time time if not request.form.get("etime"): return apology("must provide time", 400) else: etime = request.form.get("etime") # checks if valid times if timecheck(type, otime, etime) == "e": return apology("Earliest time must be earlier than optimum time", 400) elif timecheck(type, otime, etime) == "l": return apology("Latest time must be later than optimum time", 400) # checks if user entered airport if not request.form.get("airport"): return apology("must provide airport", 400) else: airport = request.form.get("airport") # checks if user entered number of passengers if not request.form.get("number"): return apology("must provide number of passengers", 400) else: number = int(request.form.get("number")) fnumber = 6 - number # insert rows = db.execute( "INSERT INTO requests (userid, airport, date, otime, number, etime, type) VALUES (:userid, :airport, :date, :otime, :number, :etime, :type)", userid=id, airport=airport, date=date, otime=otime, number=number, etime=etime, type=type) # insert into history db.execute( "INSERT INTO history (rideid, userid, type, airport, date) VALUES (:rideid, :userid, :type, :airport, :date)", rideid=rows, userid=id, airport=airport, date=date, type=type) matched = match(rows) return render_template("ordered.html", matched=matched) if request.method == "GET": return render_template("order.html", type=session["type"])
def index(): """Show portfolio of stocks""" return apology("TODO")
def errorhandler(e): """Handle error""" if not isinstance(e, HTTPException): e = InternalServerError() return apology(e.name, e.code)
def sell(): """Sell shares of stock""" # get two rows, first for one sell operations, second for condition checking, containing stocks and their shares rows = db.execute( "SELECT stock, SUM(shares) as sumshares FROM portfolio WHERE id = :currentid GROUP BY stock HAVING sumshares > 0", currentid=session["user_id"]) # returns form if method is GET if request.method == "GET": # Checks if there are no stocks to sell if len(rows) == 0: return apology("No stocks to sell.") return render_template("sell.html", htmlrows=rows) # if form is submitted, sells it after checking for things elif request.method == "POST": # Checks if shares field was left blank if not request.form.get("shares"): return apology("Please enter number of shares you want to sell.") # Checks if submitted shares is positive and less than or equal to shares in portfolio for i in range(len(rows)): if rows[i]["stock"] == request.form.get("symbol"): if int(request.form.get("shares")) < 0: return apology("Please enter a positive number.") elif int(request.form.get("shares")) > rows[i]["sumshares"]: return apology("Not enough shares.") # Looks up a stock lookupstock = lookup(request.form.get("symbol")) # Declare values to be submitted into portfolio submittedstock = request.form.get("symbol") submittedshares = -int(request.form.get("shares")) positivesubmittedshares = int(request.form.get("shares")) currentstock = lookup(submittedstock) # Logs shares submitted as a negative quantity in portfolio, along with stock symbol result = db.execute( "INSERT INTO portfolio (id, stock, shares, price) VALUES(:_id, :_stock, :_shares, :_price)", _id=session["user_id"], _stock=submittedstock, _shares=submittedshares, _price=currentstock["price"]) if not result: return apology("Could not insert into database.") # Updates cash of the user cashlist = db.execute("SELECT cash FROM users WHERE id = :currentid", currentid=session["user_id"]) cash = cashlist[0]["cash"] cash += positivesubmittedshares * currentstock["price"] result2 = db.execute( "UPDATE users SET cash = :_cash WHERE id = :currentid", _cash=cash, currentid=session["user_id"]) # Send "Transaction Complete!" message via html file return redirect("/")
def register(): """Register user""" return apology("TODO")
def history(): """Show history of transactions""" return apology("TODO")
def sell(): """Sell shares of stock""" if request.method == "POST": # Получаем информацию об акции info = {} symbol = request.form.get("symbol") if not symbol: return apology("missing symbol", 400) info = lookup(symbol) price = info["price"] # Получаем количесво денег у пользователя cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"]) cash = cash.fetchall() cash = cash[0][0] #Получаем количество акций shares = request.form.get("shares") if not shares: return apology("MISSING SHARES", 400) shares = int(shares) share_old = db.execute("SELECT count FROM stock WHERE stock_id = :id", id = session["user_id"]) share_old = share_old.fetchall() share_old = share_old[0][0] if share_old < shares : return apology("TOO MANY SHARES", 400) # Вычисляем стоимость cost = price * shares # Прибавляем стоимость к деньгам пользователя cash += cost # Обновляем данные о деньгах db.execute("UPDATE users SET cash = :cash WHERE id = :id", id = session["user_id"], cash = cash) # Обновляем данные об акциях пользователя share_old -= shares db.execute("UPDATE stock SET count = :share WHERE stock_id = :id", id = session["user_id"], share = share_old) db.execute("DELETE FROM stock WHERE count = 0") return redirect("/") else: symbols = db.execute("SELECT stock_name FROM stock WHERE stock_id = :id", id = session["user_id"]) symbols = symbols.fetchall() return render_template("sell.html", stock = symbols)
def sell(): """Sell shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": quantity = int(request.form.get("shares")) symbol = lookup(request.form.get("symbol"))['symbol'] price = lookup(symbol)['price'] # Get data from DB available = db.execute( "SELECT quantity FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) # Validate symbol if not symbol: return apology("symbol not found", 400) # Validate quantity if not quantity: return apology( "must provide valid number of stocks owned (integer)", 400) # Calculate users quantity of stocks after sell quantity_after = available[0]['quantity'] - quantity if quantity_after == 0: db.execute("DELETE FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) elif quantity_after < 0: return apology("you're trying to sell more than you own", 400) else: # Update with new value db.execute( "UPDATE stocks SET quantity = ? WHERE user_id = ? AND symbol = ?", quantity_after, session["user_id"], symbol) # Calculate users cash after sell cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]['cash'] cash_after = cash + (price * quantity) db.execute("UPDATE users SET cash = ? WHERE id = ?", cash_after, session["user_id"]) # Register transaction in transactions table db.execute( "INSERT INTO transactions(user_id, action, symbol, quantity, price, date) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], "sold", symbol, quantity, price, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Redirect user to home page flash("Transaction successful") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: # Pass from DB to select menu what user has for sell rows = db.execute( "SELECT symbol, quantity FROM stocks WHERE user_id = ?", session["user_id"]) stocks = {} for row in rows: stocks[row['symbol']] = row['quantity'] return render_template("sell.html", stocks=stocks)
def errorhandler(e): """Handle error""" return apology(e.name, e.code)
def buy(): """Buy shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Get data from input form symbol = lookup(request.form.get("symbol"))['symbol'] # Validate symbol if not symbol: return apology("symbol not found", 400) check = request.form.get("shares") if not check or not check.isdigit() or check == None: return apology("must provide valid number of stocks (integer)", 400) quantity = int(check) # Validate quantity if not quantity or quantity <= 0: return apology("must provide valid number of stocks (integer)", 400) # Calculating amount of cash for transaction price = lookup(symbol)['price'] cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]['cash'] cash_after = cash - price * quantity if cash_after < 0: return apology("not enough cash", 400) # Insert into stocks table or update row if user already has this stock user_stock = db.execute( "SELECT quantity FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) if not user_stock: db.execute( "INSERT INTO stocks(user_id, symbol, quantity) VALUES (?, ?, ?)", session["user_id"], symbol, quantity) else: quantity = quantity + user_stock[0]['quantity'] db.execute( "UPDATE stocks SET quantity = ? WHERE user_id = ? AND symbol = ?", quantity, session["user_id"], symbol) # Calculate cash left db.execute("UPDATE users SET cash = ? WHERE id = ?", cash_after, session["user_id"]) # Register transaction in transactions table db.execute( "INSERT INTO transactions(user_id, action, symbol, quantity, price, date) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], "bought", symbol, quantity, price, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Redirect user to home page flash("Transaction successful") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("buy.html")
def rand(): return apology("na ho payega!", 400)
def buy(): """Buy shares of stock""" return apology("TODO")