jrhauser11

app.py

Jun 14th, 2021
614
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import os
  2.  
  3. from cs50 import SQL
  4. from flask import Flask, flash, jsonify, redirect, render_template, request, session
  5. from flask_session import Session
  6. from tempfile import mkdtemp
  7. from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
  8. from werkzeug.security import check_password_hash, generate_password_hash
  9.  
  10. from helpers import apology, login_required, lookup, usd
  11.  
  12. # Configure application
  13. app = Flask(__name__)
  14.  
  15. # Ensure templates are auto-reloaded
  16. app.config["TEMPLATES_AUTO_RELOAD"] = True
  17.  
  18. # Ensure responses aren't cached
  19. @app.after_request
  20. def after_request(response):
  21.     response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  22.     response.headers["Expires"] = 0
  23.     response.headers["Pragma"] = "no-cache"
  24.     return response
  25.  
  26. # Custom filter
  27. app.jinja_env.filters["usd"] = usd
  28.  
  29. # Configure session to use filesystem (instead of signed cookies)
  30. app.config["SESSION_FILE_DIR"] = mkdtemp()
  31. app.config["SESSION_PERMANENT"] = False
  32. app.config["SESSION_TYPE"] = "filesystem"
  33. Session(app)
  34.  
  35. # Configure CS50 Library to use SQLite database
  36. db = SQL("sqlite:///finance.db")
  37.  
  38. # Make sure API key is set
  39. if not os.environ.get("API_KEY"):
  40.     raise RuntimeError("API_KEY not set")
  41.  
  42.  
  43. @app.route("/")
  44. @login_required
  45. def index():
  46.     """Show portfolio of stocks"""
  47.     return apology("TODO")
  48.  
  49.  
  50. @app.route("/buy", methods=["GET", "POST"])
  51. @login_required
  52. def buy():
  53.     """Buy shares of stock"""
  54.     return apology("TODO")
  55.  
  56.  
  57. @app.route("/history")
  58. @login_required
  59. def history():
  60.     """Show history of transactions"""
  61.     return apology("TODO")
  62.  
  63.  
  64. @app.route("/login", methods=["GET", "POST"])
  65. def login():
  66.     """Log user in"""
  67.  
  68.     # Forget any user_id
  69.     session.clear()
  70.  
  71.     # User reached route via POST (as by submitting a form via POST)
  72.     if request.method == "POST":
  73.  
  74.         # Ensure username was submitted
  75.         if not request.form.get("username"):
  76.             return apology("must provide username", 403)
  77.  
  78.         # Ensure password was submitted
  79.         elif not request.form.get("password"):
  80.             return apology("must provide password", 403)
  81.  
  82.         # Query database for username
  83.         rows = db.execute("SELECT * FROM users WHERE username = :username",
  84.                           username=request.form.get("username"))
  85.  
  86.         # Ensure username exists and password is correct
  87.         if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
  88.             return apology("invalid username and/or password", 403)
  89.  
  90.         # Remember which user has logged in
  91.         session["user_id"] = rows[0]["id"]
  92.  
  93.         # Redirect user to home page
  94.         return redirect("/")
  95.  
  96.     # User reached route via GET (as by clicking a link or via redirect)
  97.     else:
  98.         return render_template("login.html")
  99.  
  100.  
  101. @app.route("/logout")
  102. def logout():
  103.     """Log user out"""
  104.  
  105.     # Forget any user_id
  106.     session.clear()
  107.  
  108.     # Redirect user to login form
  109.     return redirect("/")
  110.  
  111.  
  112. @app.route("/quote", methods=["GET", "POST"])
  113. @login_required
  114. def quote():
  115.     # Check if user wants to see qoute.html
  116.     if request.method=="GET":
  117.         # Return qoute.html
  118.         return render_template("qoute.html")
  119.     # User reached via post method
  120.     else:
  121.         # store the text from the form in qouted variable after looking it up via lookup
  122.         qouted = lookup(request.form.get("symbol"))
  123.         # return qouted.html
  124.         return render_template("qouted.html")
  125.  
  126.  
  127.  
  128. @app.route("/register", methods=["GET", "POST"])
  129. def register():
  130.    
  131.     session.clear()
  132.    
  133.     if request.method=="GET":
  134.         return render_template("register.html")
  135.     #user reached route via POST method, so they want to register
  136.     else:
  137.        
  138.         #Checks they entered a username
  139.         if not request.form.get("username"):
  140.             return apology("You must enter an username", 403)
  141.        
  142.         #Checks password was entered
  143.         elif not request.form.get("password"):
  144.             return apology("You must provide password", 403)
  145.        
  146.         #Checks they retyped their password
  147.         elif not request.form.get("passwordCheck"):
  148.             return apology("Retype your password", 403)
  149.        
  150.         username = request.form.get("username")
  151.         password = request.form.get("password")
  152.         passwordCheck = request.form.get("passwordCheck")
  153.        
  154.         #This shouldn't be necessary bc of the javascript in register.html
  155.         if password != passwordCheck:
  156.             return apology("Your passwords don't match", 403)
  157.        
  158.         hash = generate_password_hash(password)
  159.  
  160.         #Insert username into users
  161.         db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=username, hash=hash)
  162.         return redirect("/login")
  163.  
  164.  
  165. @app.route("/sell", methods=["GET", "POST"])
  166. @login_required
  167. def sell():
  168.     """Sell shares of stock"""
  169.     return apology("TODO")
  170.  
  171.  
  172. def errorhandler(e):
  173.     """Handle error"""
  174.     if not isinstance(e, HTTPException):
  175.         e = InternalServerError()
  176.     return apology(e.name, e.code)
  177.  
  178.  
  179. # Listen for errors
  180. for code in default_exceptions:
  181.     app.errorhandler(code)(errorhandler)
  182.  
RAW Paste Data