Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # API key = 1Z5ZDW86BILY5Z6V
- import os
- from cs50 import SQL
- from flask import Flask, flash, redirect, render_template, request, session
- from flask_session import Session
- from tempfile import mkdtemp
- from werkzeug.exceptions import default_exceptions
- from werkzeug.security import check_password_hash, generate_password_hash
- from helpers import apology, login_required, lookup, usd
- # Ensure environment variable is set
- if not os.environ.get("API_KEY"):
- raise RuntimeError("API_KEY not set")
- # Configure application
- app = Flask(__name__)
- # 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["usd"] = usd
- # 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("/")
- @login_required
- def index():
- """Show portfolio of stocks"""
- return apology("TODO")
- @app.route("/buy", methods=["GET", "POST"])
- @login_required
- def buy():
- """Buy shares of stock"""
- # If user is inputting to form, execute the following
- if request.method == "POST":
- # Retrieve information for given symbol and integer value of number of shares
- quote = lookup(request.form.get("symbol"))
- # Retrive number of shares desired by user
- # Number type in HTML ensures that input is an integer value
- quantity = int(request.form.get("shares"))
- # If symbol not found (ie invalid), return apology
- if not quote:
- return apology("Symbol not valid", 404)
- # Return apology is value is not a positive integer
- elif quantity < 0:
- return apology("Invalid number of shares", 404)
- # Determine price of shares that are intended tobe purchased
- purchase = quote["price"] * quantity
- # Retrieve cash available for user
- row = db.execute("SELECT cash FROM users WHERE id = 5")
- # Check if user has enough cash, if not return apology
- if row[0]["cash"] < purchase:
- return apology("Not enough cash", 403)
- db.execute("UPDATE users SET cash = cash - :p WHERE id = 1", p=purchase)
- db.execute("UPDATE shares SET stock = :s WHERE id = 1", s = quote['symbol'])
- db.execute("UPDATE shares SET quantity = :q WHERE id = 1", q = quantity)
- else:
- return render_template("buy.html")
- @app.route("/history")
- @login_required
- def history():
- """Show history of transactions"""
- return apology("TODO")
- @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 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")
- @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":
- quote = lookup(request.form.get("symbol"))
- if not quote:
- return apology("Symbol not valid", 404)
- return render_template("quoted.html", price = quote["price"], symbol = quote["symbol"])
- else:
- return render_template("quote.html")
- @app.route("/register", methods=["GET", "POST"])
- def register():
- """Register user"""
- 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)
- # Ensure passwords match
- elif request.form.get("password") != request.form.get("confirmation"):
- return apology("Passwords must match")
- # Hash password
- hashpassword = generate_password_hash(request.form.get("password"))
- # Add username and password to database
- result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)",
- username = request.form.get("username"), hash = hashpassword)
- # Return apology is username is not unique in database
- if not result:
- return apology("Username already taken")
- # Query database for username
- rows = db.execute("SELECT * FROM users WHERE username = :username",
- username = request.form.get("username"))
- # Once registered, store their id in session
- 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("register.html")
- @app.route("/sell", methods=["GET", "POST"])
- @login_required
- def sell():
- """Sell shares of stock"""
- return apology("TODO")
- def errorhandler(e):
- """Handle error"""
- return apology(e.name, e.code)
- # listen for errors
- for code in default_exceptions:
- app.errorhandler(code)(errorhandler)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement