Advertisement
Guest User

Untitled

a guest
Apr 5th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.35 KB | None | 0 0
  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.  
  39. @app.route("/")
  40. @login_required
  41. def index():
  42.     """Show portfolio of stocks"""
  43.  
  44.     return render_template("index.html")
  45.  
  46.  
  47. @app.route("/buy", methods=["GET", "POST"])
  48. @login_required
  49. def buy():
  50.     """Buy shares of stock"""
  51.     if request.method == "POST":
  52.         symbol = request.form.get("symbol")
  53.         if not symbol:
  54.             return apology("missing symbol", 400)
  55.         elif not lookup(symbol):
  56.             return apology("invaild symbol", 400)
  57.         elif not int(request.form.get("shares")) > 0:
  58.             return apology("Share must be greater than 0", 400)
  59.  
  60.         userid = session["user_id"]
  61.         my_dict=lookup(symbol)
  62.         rows = db.execute("SELECT cash FROM users WHERE id = :userid",userid=userid)
  63.         cash = float(rows[0]["cash"])
  64.         symbol = my_dict["symbol"]
  65.         companyname = my_dict["name"]
  66.         shares = int(request.form.get("shares"))
  67.         price = float(my_dict["price"])
  68.         total = price * shares
  69.  
  70.         if cash < total:
  71.             return apology("can't afford", 400)
  72.         db.execute("INSERT INTO transaction (userid,symbol,companyname,shares,price,total) VALUES (:userid, :symbol, :companyname, :shares, :price, :total) ",userid=userid, symbol=symbol, companyname=companyname, shares=shares, price=price, total=total)
  73.         db.execute("UPDATE users SET cash = cash - :total WHERE id = :userid",total,userid=userid)
  74.  
  75.     else:
  76.         return render_template("buy.html")
  77.  
  78.  
  79. @app.route("/check", methods=["GET"])
  80. def check():
  81.     """Return true if username available, else false, in JSON format"""
  82.  
  83.     return jsonify("TODO")
  84.  
  85.  
  86. @app.route("/history")
  87. @login_required
  88. def history():
  89.     """Show history of transactions"""
  90.     return apology("TODO")
  91.  
  92.  
  93. @app.route("/login", methods=["GET", "POST"])
  94. def login():
  95.     """Log user in"""
  96.  
  97.     # Forget any user_id
  98.     session.clear()
  99.  
  100.     # User reached route via POST (as by submitting a form via POST)
  101.     if request.method == "POST":
  102.  
  103.         # Ensure username was submitted
  104.         if not request.form.get("username"):
  105.             return apology("must provide username", 403)
  106.  
  107.         # Ensure password was submitted
  108.         elif not request.form.get("password"):
  109.             return apology("must provide password", 403)
  110.  
  111.         # Query database for username
  112.         rows = db.execute("SELECT * FROM users WHERE username = :username",
  113.                           username=request.form.get("username"))
  114.  
  115.         # Ensure username exists and password is correct
  116.         if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
  117.             return apology("invalid username and/or password", 403)
  118.  
  119.         # Remember which user has logged in
  120.         session["user_id"] = rows[0]["id"]
  121.  
  122.         # Redirect user to home page
  123.         return redirect("/")
  124.  
  125.     # User reached route via GET (as by clicking a link or via redirect)
  126.     else:
  127.         return render_template("login.html")
  128.  
  129. @app.route("/logout")
  130. def logout():
  131.     """Log user out"""
  132.  
  133.     # Forget any user_id
  134.     session.clear()
  135.  
  136.     # Redirect user to login form
  137.     return redirect("/")
  138.  
  139. @app.route("/quote", methods=["GET", "POST"])
  140. @login_required
  141. def quote():
  142.     """Get stock quote."""
  143.     if request.method == "POST":
  144.         if not request.form.get("symbol"):
  145.             return apology("missing symbol", 400)
  146.         symbol = request.form.get("symbol")
  147.         if lookup(symbol):
  148.             my_dict = lookup(symbol)
  149.             return render_template("quoted.html",
  150.             name = my_dict['name'], price = usd(my_dict['price']), sym = my_dict['symbol'])
  151.         else:
  152.             return apology("invalid symbol", 400)
  153.     else:
  154.         return render_template("quote.html")
  155.  
  156. @app.route("/register", methods=["GET", "POST"])
  157. def register():
  158.     """Register user"""
  159.  
  160.     if request.method == "POST":
  161.         # Ensure username was submitted
  162.         if not request.form.get("username"):
  163.             return apology("must provide username", 403)
  164.  
  165.         # Ensure password is correct
  166.         elif not request.form.get("password"):
  167.             return apology("must provide password", 403)
  168.         elif not request.form.get("confirmation"):
  169.             return apology("must confirm password", 403)
  170.         elif request.form.get("password") != request.form.get("confirmation"):
  171.             return apology("not same password", 403)
  172.         # Insert database for username
  173.         result = db.execute("INSERT INTO users (username,hash) VALUES (:username, :password)",
  174.         username=request.form.get("username")
  175.         ,password=generate_password_hash(request.form.get("password")))
  176.         if not result:
  177.             return apology("Try different username", 403)
  178.         # Redirect user to home page
  179.         return redirect("/")
  180.     else:
  181.         return render_template("register.html")
  182.  
  183. @app.route("/sell", methods=["GET", "POST"])
  184. @login_required
  185. def sell():
  186.     """Sell shares of stock"""
  187.     return apology("TODO")
  188.  
  189. def errorhandler(e):
  190.     """Handle error"""
  191.     if not isinstance(e, HTTPException):
  192.         e = InternalServerError()
  193.     return apology(e.name, e.code)
  194.  
  195.  
  196. # Listen for errors
  197. for code in default_exceptions:
  198.     app.errorhandler(code)(errorhandler)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement