Guest User

Untitled

a guest
Oct 5th, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.67 KB | None | 0 0
  1. import os
  2.  
  3. from cs50 import SQL
  4. from flask import Flask, flash, redirect, render_template, request, session
  5. from flask_session import Session
  6. from tempfile import mkdtemp
  7. from werkzeug.exceptions import default_exceptions
  8. from werkzeug.security import check_password_hash, generate_password_hash
  9. import os
  10.  
  11. from helpers import apology, login_required, lookup, usd
  12.  
  13.  
  14.  
  15. # Configure application
  16. app = Flask(__name__)
  17.  
  18. # Ensure templates are auto-reloaded
  19. app.config["TEMPLATES_AUTO_RELOAD"] = True
  20.  
  21. APP_ROOT = os.path.dirname(os.path.abspath(__file__))
  22.  
  23.  
  24. # Ensure responses aren't cached
  25. @app.after_request
  26. def after_request(response):
  27.     response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  28.     response.headers["Expires"] = 0
  29.     response.headers["Pragma"] = "no-cache"
  30.     return response
  31.  
  32. # Custom filter
  33. app.jinja_env.filters["usd"] = usd
  34.  
  35. # Configure session to use filesystem (instead of signed cookies)
  36. app.config["SESSION_FILE_DIR"] = mkdtemp()
  37. app.config["SESSION_PERMANENT"] = False
  38. app.config["SESSION_TYPE"] = "filesystem"
  39. Session(app)
  40.  
  41. # Configure CS50 Library to use SQLite database
  42. db = SQL("sqlite:///project.db")
  43.  
  44.  
  45. @app.route("/", methods=["GET", "POST"])
  46. @login_required
  47. def index():
  48.     if request.method == "GET":
  49.         rows = db.execute("Select * from books")
  50.         return render_template("index.html", rows = rows)
  51.     else:
  52.         search = request.form.get("search").title()
  53.         k = len(search)
  54.         tmp = []
  55.         for i in range(k):
  56.             tmp.append("%")
  57.             tmp.append(search[i])
  58.         tmp.append("%")
  59.         mac = "".join(tmp)
  60.  
  61.         crit = request.form.get("sby")
  62.  
  63.         if not crit :
  64.             rows = db.execute("Select * from books")
  65.             return render_template("index.html", rows = rows)
  66.  
  67.         if crit == "n":
  68.             rows = db.execute("Select * from books where bookname like :ser", ser = mac)
  69.  
  70.         if crit == "a":
  71.             rows = db.execute("Select * from books where author like :ser", ser = mac)
  72.  
  73.         if crit == "c":
  74.             rows = db.execute("Select * from books where class like :ser", ser = mac)
  75.  
  76.         if crit == "t":
  77.             rows = db.execute("Select * from books where type like :ser", ser = mac)
  78.  
  79.         if crit == "s":
  80.             rows = db.execute("Select * from books where subject like :ser", ser = mac)
  81.  
  82.         return render_template("index.html", rows = rows)
  83.  
  84.  
  85. @app.route("/about_us")
  86. @login_required
  87. def about_us():
  88.     return render_template("about_us.html")
  89.  
  90. @app.route("/share", methods=["GET", "POST"])
  91. @login_required
  92. def buy():
  93.     if request.method == "GET":
  94.  
  95.         return render_template("share.html")
  96.  
  97.     else:
  98.  
  99.         # get all the values from form
  100.  
  101.         target = os.path.join(APP_ROOT, 'static/images/')
  102.  
  103.         if not os.path.isdir(target):
  104.             os.mkdir(target)
  105.  
  106.         mobile = request.form.get("mobile")
  107.         email = request.form.get("email")
  108.         city = request.form.get("city").title()
  109.         state = request.form.get("state").title()
  110.         book = request.form.get("book").title()
  111.         author = request.form.get("author").title()
  112.         typee = request.form.get("type")
  113.         subject = request.form.get("subject")
  114.         clas = request.form.get("class")
  115.         cost = request.form.get("cost")
  116.         pic = request.files.getlist("photo")
  117.  
  118.         tmp = [mobile, email, city, state, book, author, typee, subject, clas, cost, pic]
  119.  
  120.         for k in tmp:
  121.             if not k:
  122.                 return render_template("share.html")
  123.  
  124.         for file in request.files.getlist("photo"):
  125.             filename = book + "_" + file.filename
  126.             destination = "/".join([target, filename])
  127.         file.save(destination)
  128.  
  129.         img_name = filename
  130.  
  131.         # insert values in database
  132.  
  133.         db.execute("Insert into books(user_id, mobile, email, city, state, bookname, author, type, subject, class, cost, img_name) values(:i_d, :mob, :e, :city, :state, :bname, :author, :typee, :sub, :clas, :cost, :img)",
  134.         i_d = session["user_id"], mob = mobile, e = email, city = city, state = state, bname = book, author = author, typee = typee, sub = subject, clas = clas, cost = cost, img = img_name)
  135.  
  136.         return redirect("/")
  137.  
  138. @app.route("/remove", methods=["GET", "POST"])
  139. @login_required
  140. def quote():
  141.     if request.method == "GET":
  142.         rows = db.execute("Select * from books where user_id = :i_d", i_d = session["user_id"])
  143.  
  144.         return render_template("remove.html", rows = rows)
  145.     else:
  146.  
  147.         bname = request.form.get("book")
  148.         db.execute("DELETE from books where bookname = :name", name = bname)
  149.         return redirect("/")
  150.  
  151. @app.route("/<book_name>", methods=["GET", "POST"])
  152. @login_required
  153. def about(book_name):
  154.     rows = db.execute("Select * from books where bookname = :book", book = book_name)
  155.  
  156.     return render_template("book.html", rows = rows)
  157.  
  158.  
  159.  
  160. @app.route("/login", methods=["GET", "POST"])
  161. def login():
  162.     """Log user in"""
  163.  
  164.     # Forget any user_id
  165.     session.clear()
  166.  
  167.     # User reached route via POST (as by submitting a form via POST)
  168.     if request.method == "POST":
  169.  
  170.         # Ensure username was submitted
  171.         if not request.form.get("username"):
  172.             return apology("must provide username", 403)
  173.  
  174.         # Ensure password was submitted
  175.         elif not request.form.get("password"):
  176.             return apology("must provide password", 403)
  177.  
  178.         # Query database for username
  179.         rows = db.execute("SELECT * FROM users WHERE username = :username;",
  180.                           username=request.form.get("username"))
  181.  
  182.         # Ensure username exists and password is correct
  183.         if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
  184.             return apology("invalid username and/or password", 403)
  185.  
  186.         # Remember which user has logged in
  187.         session["user_id"] = rows[0]["user_id"]
  188.  
  189.         # Redirect user to home page
  190.         return redirect("/")
  191.  
  192.     # User reached route via GET (as by clicking a link or via redirect)
  193.     else:
  194.         return render_template("login.html")
  195.  
  196.  
  197. @app.route("/logout")
  198. def logout():
  199.     """Log user out"""
  200.  
  201.     # Forget any user_id
  202.     session.clear()
  203.  
  204.     # Redirect user to login form
  205.     return redirect("/")
  206.  
  207.  
  208. @app.route("/register", methods=["GET", "POST"])
  209. def register():
  210.     """Register user"""
  211.     # User reached route via GET (as by clicking a link or via redirect)
  212.     if request.method == "POST":
  213.         name = request.form.get("username")
  214.         password = request.form.get("password")
  215.         if not name or not password:
  216.             return apology("Invalid")
  217.         test = request.form.get("confirmation")
  218.         if password != test:
  219.             return apology("Passwords did not match")
  220.         phash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8)
  221.         result = db.execute("Select * from users where username = :name;", name = name)
  222.         if result != [] :
  223.             return apology("Username alredy exists")
  224.         db.execute("Insert into users(username,hash) values(:username,:hash);", username = request.form.get("username"), hash = phash)
  225.         row = db.execute("Select user_id from users where username = :uname;", uname = name)
  226.         session["user_id"] = row[0]["user_id"]
  227.         #db.execute("Insert into portfolio(user_id) values(:i)", i = row[0])
  228.         return redirect("/")
  229.  
  230.     else:
  231.         return render_template("register.html")
  232.  
  233. def errorhandler(e):
  234.     """Handle error"""
  235.     return apology(e.name, e.code)
  236.  
  237. # listen for errors
  238. for code in default_exceptions:
  239.     app.errorhandler(code)(errorhandler)
Add Comment
Please, Sign In to add comment