ahmedraza

application.py

Feb 18th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.88 KB | None | 0 0
  1. from cs50 import SQL
  2. from flask import Flask, flash, redirect, render_template, request, session, url_for
  3. from flask_session import Session
  4. from passlib.apps import custom_app_context as pwd_context
  5. from tempfile import gettempdir
  6.  
  7. from helpers import *
  8.  
  9. # configure application
  10. app = Flask(__name__)
  11.  
  12. # ensure responses aren't cached
  13. if app.config["DEBUG"]:
  14.     @app.after_request
  15.     def after_request(response):
  16.         response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  17.         response.headers["Expires"] = 0
  18.         response.headers["Pragma"] = "no-cache"
  19.         return response
  20.  
  21. # custom filter
  22. app.jinja_env.filters["usd"] = usd
  23.  
  24. # configure session to use filesystem (instead of signed cookies)
  25. app.config["SESSION_FILE_DIR"] = gettempdir()
  26. app.config["SESSION_PERMANENT"] = False
  27. app.config["SESSION_TYPE"] = "filesystem"
  28. Session(app)
  29.  
  30. # configure CS50 Library to use SQLite database
  31. db = SQL("sqlite:///finance.db")
  32.  
  33. @app.route("/")
  34. @login_required
  35. def index():
  36.     return apology("TODO")
  37.  
  38. @app.route("/buy", methods=["GET", "POST"])
  39. @login_required
  40. def buy():
  41.     """Buy shares of stock."""
  42.     return apology("TODO")
  43.  
  44. @app.route("/history")
  45. @login_required
  46. def history():
  47.     """Show history of transactions."""
  48.     return apology("TODO")
  49.  
  50. @app.route("/login", methods=["GET", "POST"])
  51. def login():
  52.     """Log user in."""
  53.  
  54.     # forget any user_id
  55.     session.clear()
  56.  
  57.     # if user reached route via POST (as by submitting a form via POST)
  58.     if request.method == "POST":
  59.  
  60.         # ensure username was submitted
  61.         if not request.form.get("username"):
  62.             return apology("must provide username")
  63.  
  64.         # ensure password was submitted
  65.         elif not request.form.get("password"):
  66.             return apology("must provide password")
  67.  
  68.         # query database for username
  69.         rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
  70.  
  71.         # ensure username exists and password is correct
  72.         if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
  73.             return apology("invalid username and/or password")
  74.  
  75.         # remember which user has logged in
  76.         session["user_id"] = rows[0]["id"]
  77.  
  78.         # redirect user to home page
  79.         return redirect(url_for("index"))
  80.  
  81.     # else if user reached route via GET (as by clicking a link or via redirect)
  82.     else:
  83.         return render_template("login.html")
  84.  
  85. @app.route("/logout")
  86. def logout():
  87.     """Log user out."""
  88.  
  89.     # forget any user_id
  90.     session.clear()
  91.  
  92.     # redirect user to login form
  93.     return redirect(url_for("login"))
  94.  
  95. @app.route("/quote", methods=["GET", "POST"])
  96. @login_required
  97. def quote():
  98.     """Get stock quote."""
  99.     return apology("TODO")
  100.  
  101. @app.route("/register", methods=["GET","POST"])
  102. def register():
  103.     # forget any user_id
  104.     session.clear()
  105.     # if user reached route via POST (as by submitting a form via POST)
  106.     if request.method == "POST":
  107.                # ensure username was submitted
  108.         if not request.form.get("username"):
  109.             return apology("must provide username")
  110.            
  111.         # ensure password was submitted
  112.         if not request.form.get("password"):
  113.             return apology("must provide password")
  114.         #ensure again password submitted
  115.         if not request.form.get("again_password"):
  116.             return apology("must provide password again")
  117.         #ensure both password match    
  118.         if request.form.get("password") == request.form.get("again_password"):
  119.             #query database for username
  120.             rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
  121.            #Ensure usename don't exist already
  122.             if  len(rows) == 0:    
  123.                 #Encrypt password
  124.                 h = pwd_context.encrypt(request.form.get("password"))
  125.                 #insert username and password to SQL data base
  126.                 key = db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=request.form.get("username"), hash=h)
  127.                 #Remember user id after successful register.
  128.                 session["user_id"] = key
  129.  
  130.                 # redirect user to home page
  131.                 return redirect(url_for("index"))
  132.                
  133.             else:
  134.                 #return apology if username already exist
  135.                 return apology("Username already exist")
  136.         else:
  137.             #return apology if both password don't match with each other
  138.             return apology("both password should match")
  139.     #Return to register.html and use post mathod        
  140.     else:
  141.         return render_template("register.html")
  142.  
  143.  
  144. @app.route("/sell", methods=["GET", "POST"])
  145. @login_required
  146. def sell():
  147.     """Sell shares of stock."""
  148.     return apology("TODO")
Add Comment
Please, Sign In to add comment