ahmedraza

application.py

Apr 4th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.31 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. from collections import defaultdict
  7.  
  8. from helpers import *
  9.  
  10. # configure application
  11. app = Flask(__name__)
  12.  
  13. # ensure responses aren't cached
  14. if app.config["DEBUG"]:
  15.     @app.after_request
  16.     def after_request(response):
  17.         response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  18.         response.headers["Expires"] = 0
  19.         response.headers["Pragma"] = "no-cache"
  20.         return response
  21.  
  22. # custom filter
  23. app.jinja_env.filters["usd"] = usd
  24.  
  25. # configure session to use filesystem (instead of signed cookies)
  26. app.config["SESSION_FILE_DIR"] = gettempdir()
  27. app.config["SESSION_PERMANENT"] = False
  28. app.config["SESSION_TYPE"] = "filesystem"
  29. Session(app)
  30.  
  31. # configure CS50 Library to use SQLite database
  32. db = SQL("sqlite:///finance.db")
  33.  
  34. @app.route("/")
  35. @login_required
  36. def index():
  37.     #Remember id
  38.     ide = session["user_id"]
  39.     #Take all information from users data table, used for determining cash of user.
  40.     row = db.execute ("select * from users where id = :ii" , ii = ide)
  41.     #take info about sahres user has bought
  42.     symb = db.execute ("select * from portfolio where id = :ii GROUP BY symbol ORDER BY symbol" , ii = ide)
  43.     #if user has not bought any sahres then display noshare html file.
  44.     if not symb:
  45.     #Return user a message in html and his cash holdings.
  46.         return render_template ("noshares.html",cash = row[0]["cash"])
  47.     else:
  48.         total = 0
  49.         #Iterrate over each element in symb
  50.         for share in symb:
  51.             #Get symbol of each element
  52.             symbol = share ["symbol"]
  53.             #Lookup current price of that specific symbol/sahre
  54.             quote = lookup (symbol)
  55.             #save each current price
  56.             share["quoteprice"] = quote["price"]
  57.             #This total formula works for only 1 share because my idex still don't sum the shares.
  58.             total += (quote["price"] * share ['shares'])
  59.         #grand is equel to total + the cash user has in his account
  60.         grand = total + row[0]["cash"]    
  61.         #render values    
  62.         return render_template ("index.html", symbol = symb,cash = row[0]["cash"],gtotal = grand)
  63.            
  64.            
  65. @app.route("/buy", methods=["GET", "POST"])
  66. @login_required
  67. def buy():
  68.     """Buy shares of stock."""
  69.     if request.method == "POST":
  70.         #take symbol from user
  71.         symbl = request.form.get("symbol")
  72.         if not symbl:
  73.             return apology ("Must enter the symbol")
  74.         #Number of shares to buy    
  75.         num = request.form.get("number")
  76.         number = float (num)
  77.         if number is None or number == '' or number < 1:
  78.             return apology ("Please enter valid number of stocks to buy")
  79.        
  80.            
  81.         #Lookup and save dict in quoted    
  82.         quoted = lookup(symbl)
  83.         #If symbol is invalid return apology
  84.         if not quoted:
  85.             return apology ("Invalid stock")
  86.         else:
  87.             #qtd saves price of share
  88.             qtd = quoted["price"]
  89.             #price of single share * Number of sahres required to buy
  90.             prc = float(qtd) * number
  91.             #remember session id
  92.             ide = session["user_id"]
  93.            
  94.             csh = db.execute("SELECT * FROM users WHERE id = :ide", ide = ide)
  95.             #Only go forward if user have enough
  96.             if prc <= csh[0]["cash"]:
  97.                 db.execute("INSERT INTO portfolio (id, symbol,price,shares) VALUES (:ide, :symbol, :price, :shares)", ide = ide,symbol = symbl, price = prc, shares = number)
  98.                 db.execute("UPDATE users SET cash = :cash WHERE id = :ide",cash = csh[0]["cash"] - prc, ide = ide)
  99.                 return render_template("index.html")
  100.             else:
  101.                 return apology ("You don't have enough cash to buy these stocks")
  102.     else:
  103.         return render_template("buy.html")
  104.  
  105. @app.route("/history")
  106. @login_required
  107. def history():
  108.     """Show history of transactions."""
  109.     return apology("TODO")
  110.  
  111. @app.route("/login", methods=["GET", "POST"])
  112. def login():
  113.     """Log user in."""
  114.  
  115.     # forget any user_id
  116.     session.clear()
  117.  
  118.     # if user reached route via POST (as by submitting a form via POST)
  119.     if request.method == "POST":
  120.  
  121.         # ensure username was submitted
  122.         if not request.form.get("username"):
  123.             return apology("must provide username")
  124.  
  125.         # ensure password was submitted
  126.         elif not request.form.get("password"):
  127.             return apology("must provide password")
  128.  
  129.         # query database for username
  130.         rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
  131.  
  132.         # ensure username exists and password is correct
  133.         if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
  134.             return apology("invalid username and/or password")
  135.  
  136.         # remember which user has logged in
  137.         session["user_id"] = rows[0]["id"]
  138.  
  139.         # redirect user to home page
  140.         return redirect(url_for("index"))
  141.  
  142.     # else if user reached route via GET (as by clicking a link or via redirect)
  143.     else:
  144.         return render_template("login.html")
  145.  
  146. @app.route("/logout")
  147. def logout():
  148.     """Log user out."""
  149.  
  150.     # forget any user_id
  151.     session.clear()
  152.  
  153.     # redirect user to login form
  154.     return redirect(url_for("login"))
  155.  
  156. @app.route("/quote", methods=["GET","POST"])
  157. @login_required
  158. def quote():
  159.     #Ensure method of access is get
  160.     if request.method == "POST":
  161.         #take symbol from user
  162.         symbl = request.form.get("symbol")
  163.         if not symbl:
  164.             return apology ("Must enter the symbol")
  165.         #Lookup and save dict in quoted    
  166.         quoted = lookup(symbl)
  167.         #If symbol is invalid return apology
  168.         if not quoted:
  169.             return apology ("Invalid stock")
  170.         #render values to quoted.html    
  171.         else:    
  172.        
  173.             return render_template ("quoted.html", **quoted)
  174.     else:
  175.         return render_template("quote.html")
  176.  
  177. @app.route("/register", methods=["GET","POST"])
  178. def register():
  179.     # forget any user_id
  180.     session.clear()
  181.     # if user reached route via POST (as by submitting a form via POST)
  182.     if request.method == "POST":
  183.                # ensure username was submitted
  184.         if not request.form.get("username"):
  185.             return apology("must provide username")
  186.            
  187.         # ensure password was submitted
  188.         if not request.form.get("password"):
  189.             return apology("must provide password")
  190.         #ensure again password submitted
  191.         if not request.form.get("again_password"):
  192.             return apology("must provide password again")
  193.         #ensure both password match    
  194.         if request.form.get("password") == request.form.get("again_password"):
  195.             #query database for username
  196.             rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
  197.            #Ensure usename don't exist already
  198.             if  len(rows) == 0:    
  199.                 #Encrypt password
  200.                 h = pwd_context.encrypt(request.form.get("password"))
  201.                 #insert username and password to SQL data base
  202.                 key = db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=request.form.get("username"), hash=h)
  203.                 #Remember user id after successful register.
  204.                 session["user_id"] = key
  205.  
  206.                 # redirect user to home page
  207.                 return redirect(url_for("index"))
  208.                
  209.             else:
  210.                 #return apology if username already exist
  211.                 return apology("Username already exist")
  212.         else:
  213.             #return apology if both password don't match with each other
  214.             return apology("both password should match")
  215.     #Return to register.html and use post mathod        
  216.     else:
  217.         return render_template("register.html")
  218.  
  219. @app.route("/sell", methods=["GET", "POST"])
  220. @login_required
  221. def sell():
  222.     """Sell shares of stock."""
  223.     return apology("TODO")
Add Comment
Please, Sign In to add comment