Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from cs50 import SQL
- from flask import Flask, flash, redirect, render_template, request, session, url_for
- from flask_session import Session
- from tempfile import mkdtemp
- from werkzeug.exceptions import default_exceptions
- from passlib.apps import custom_app_context as pwd_context
- from werkzeug.security import check_password_hash, generate_password_hash
- from helpers import apology, login_required, lookup, gbp
- # Ensure environment variable is set
- if not os.environ.get("API_KEY"):
- raise RuntimeError("API_KEY not set")
- # Configure application
- app = Flask(__name__)
- #api key
- # export API_KEY=CH6XN0H8ULI6ZE4E
- # Ensure templates are auto-reloaded
- app.config["TEMPLATES_AUTO_RELOAD"] = True
- # Ensure responses aren't cached
- @app.after_request
- def after_request(response):
- response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
- response.headers["Expires"] = 0
- response.headers["Pragma"] = "no-cache"
- return response
- # Custom filter
- app.jinja_env.filters["gbp"] = gbp
- # Configure session to use filesystem (instead of signed cookies)
- app.config["SESSION_FILE_DIR"] = mkdtemp()
- app.config["SESSION_PERMANENT"] = False
- app.config["SESSION_TYPE"] = "filesystem"
- Session(app)
- # Configure CS50 Library to use SQLite database
- db = SQL("sqlite:///finance.db")
- @app.route('/', defaults={'alt': False})
- @app.route('/index.html', defaults={'alt': True})
- @login_required
- def index():
- """Show portfolio of stocks"""
- cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
- grandtotal = cash[0]["cash"]
- # obtain stock info from portfolio database
- stocks = db.execute("SELECT symbol, quantity FROM transactions WHERE u_id = :u_id", u_id=session["user_id"])
- # for every stock in the user's portfolio, assign dict key/values for use in html/jinja
- for stock in stocks:
- symbol = str(stock["symbol"])
- shares = int(stock["quantity"])
- name = ""
- price = ""
- total = ""
- quote = lookup(symbol)
- stock["name"] = quote["name"]
- stock["price"] = "{:.2f}".format(quote["price"])
- stock["total"] = "{:.2f}".format(quote["price"] * shares)
- stock["grandtotal"] = quote["price"] * shares
- grandtotal += stock["grandtotal"]
- # format grandtotal to force 2 decimal places
- grandtotal = "{:.2f}".format(grandtotal)
- # render index page with some given values
- return render_template("index.html", stocks = stocks, cash = cash, grandtotal = grandtotal)
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- """Buy shares of stock"""
- if request.method == "POST":
- # if symbol is empty return apology
- if not request.form.get("symbol"):
- return apology("enter a symbol")
- # if shares is empty
- elif not request.form.get("shares"):
- return apology("enter shares")
- elif not request.form.get("shares").isdigit():
- return apology("enter a number")
- shares = int(request.form.get("shares"))
- symbol = lookup(request.form.get("symbol"))
- money = db.execute("SELECT cash FROM users WHERE id = :id", \
- id=session["user_id"])
- money = int(money[0]['cash'])
- if (shares * symbol['price']) > money:
- return apology("can't afford")
- else:
- db.execute("INSERT INTO transactions (symbol, quantity, price, u_id) VALUES (:symbol, :quantity, :price, :u_id);", \
- symbol=symbol['symbol'], quantity=shares, price=symbol['price'], u_id=session["user_id"])
- # update cash (define old_balance)
- db.execute("UPDATE users SET cash=cash-:total_price WHERE id=:user_id;", total_price=shares*symbol['price'], \
- user_id=session["user_id"])
- return redirect(url_for("index"))
- return apology("nearly")
- else:
- return render_template("buy.html")
- @app.route("/history")
- @login_required
- def history():
- """Show history of transactions"""
- stocks = db.execute("SELECT symbol, quantity, price, date_time FROM transactions WHERE u_id=:u_id", u_id=session['user_id'])
- for stock in stocks:
- stock['price'] = gbp(stock['price'])
- return render_template("history.html", stocks=stocks)
- @app.route("/login", methods=["GET", "POST"])
- 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 pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
- 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")
- @app.route("/logout")
- def logout():
- """Log user out"""
- # Forget any user_id
- session.clear()
- # Redirect user to login form
- return redirect("/")
- @app.route("/quote", methods=["GET", "POST"])
- @login_required
- def quote():
- """Get stock quote."""
- if request.method == "POST":
- rows = lookup(request.form.get("symbol"))
- if not rows:
- return apology("Invalid Symbol")
- return render_template("quoted.html", stock=rows)
- else:
- return render_template("quote.html")
- @app.route("/register", methods=["GET", "POST"])
- def register():
- """Register user"""
- if request.method == "POST":
- # Ensure username was submitted
- if not request.form.get("username"):
- return apology("must provide username")
- elif not request.form.get("password"):
- return apology("must provide password")
- elif request.form.get("confirmation") != request.form.get("password"):
- return apology("passwords don't match")
- password = request.form.get("password")
- hash = pwd_context.hash(password)
- result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
- if not result:
- return apology("username exists")
- user_id = db.execute("SELECT id FROM users WHERE username = :username",\
- username=request.form.get("username"))
- session['user_id'] = user_id[0]['id']
- return render_template("index.html")
- else:
- return render_template("register.html")
- @app.route("/sell", methods=["GET", "POST"])
- @login_required
- def sell():
- if request.method == "POST":
- # if symbol is empty return apology
- if not request.form.get("symbol"):
- return apology("enter a symbol")
- # if shares is empty
- elif not request.form.get("shares"):
- return apology("enter shares")
- elif not request.form.get("shares").isdigit():
- return apology("enter a number")
- shares = int(request.form.get("shares"))
- symbol = lookup(request.form.get("symbol"))
- checkstock = db.execute("SELECT SUM(quantity) FROM transactions WHERE u_id = :u_id AND symbol = :symbol", u_id=session["user_id"], symbol=symbol["symbol"])
- if not checkstock[0]['SUM(quantity)']:
- return apology("you don't own this")
- if shares > checkstock[0]['SUM(quantity)']:
- return apology("you don't own that many stocks")
- db.execute("INSERT INTO transactions (symbol, quantity, price, u_id) VALUES (:symbol, :quantity, :price, :u_id);", \
- symbol=symbol['symbol'], quantity=-shares, price=symbol['price'], u_id=session["user_id"])
- # update cash
- db.execute("UPDATE users SET cash = cash + :total_price WHERE id = :user_id;", total_price=shares*symbol['price'], \
- user_id=session["user_id"])
- return redirect(url_for('index'))
- else:
- return render_template("sell.html")
- @app.route("/freemoney", methods=["GET", "POST"])
- def freemoney():
- if request.method == "POST":
- try:
- freemoney = int(request.form.get("freemoney"))
- if not request.form.get("freemoney"):
- return apology("Do you want money or not?")
- elif freemoney > 1000:
- return apology("Not that much, sorry")
- except:
- return apology("Not that much, sorry")
- db.execute("UPDATE users SET cash = cash + :freemoney WHERE id = :id", freemoney=freemoney, id=session["user_id"])
- return render_template("buy.html")
- else:
- return render_template("freemoney.html")
- def errorhandler(e):
- """Handle error"""
- return apology(e.name, e.code)
- # listen for errors
- for code in default_exceptions:
- app.errorhandler(code)(errorhandler)
Add Comment
Please, Sign In to add comment