bocajbee

final_project_application.py

Aug 4th, 2020 (edited)
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.19 KB | None | 0 0
  1. import os
  2.  
  3. # https://pypi.org/project/flask-googlemaps/
  4.  
  5. # Import the modules that we will want to use
  6. from cs50 import SQL
  7. from flask import Flask, flash, jsonify, redirect, render_template, request, session
  8. from flask_session import Session
  9. from flask_googlemaps import GoogleMaps
  10. from tempfile import mkdtemp
  11. from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
  12. from werkzeug.security import check_password_hash, generate_password_hash
  13. import config
  14.  
  15. from helpers import login_required
  16.  
  17. # Configure application
  18. app = Flask(__name__)
  19. # Ensure that user sessions when they are logged in are not perm
  20. app.config["SESSION_PERMANENT"] = False
  21. # Ensure the location that we want to store the data for user sessions is going to be in the file system of the webserver we'll be running this application from (CS50 IDE)
  22. app.config["SESSION_TYPE"] = "filesystem"
  23. # We would like to enable sessions for this particular flask web app
  24. Session(app)
  25.  
  26. # Ensure templates are auto-reloaded when sent and recieved
  27. app.config["TEMPLATES_AUTO_RELOAD"] = True
  28.  
  29. # set the maps api key as config
  30. app.config['GOOGLEMAPS_KEY'] = "8JZ7i18MjFuM35dJHq70n3Hx4"
  31.  
  32. # Initialize the extension
  33. GoogleMaps(app)
  34.  
  35. # Ensure responses aren't cached
  36. @app.after_request
  37. def after_request(response):
  38.     response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  39.     response.headers["Expires"] = 0
  40.     response.headers["Pragma"] = "no-cache"
  41.     return response
  42.  
  43. # Configure CS50 Library to use SQLite database
  44. db = SQL("sqlite:///parks.db")
  45.  
  46. # app route to map out 1 park
  47. @app.route("/")
  48. @login_required
  49. def index():
  50.     """Homepage with Park locator"""
  51.  
  52.     index_park_info = send_to_index()
  53.  
  54.     return render_template("index.html", index_park_info=index_park_info)
  55.  
  56. # app route to search all parks
  57. @app.route("/allparks", methods=["GET", "POST"])
  58. @login_required
  59. def allparks():
  60.     """Page with all parks"""
  61.     if request.method == "GET":
  62.         return render_template("allparks.html")
  63.  
  64. # app route to see your saved parks
  65. @app.route("/myparks", methods=["GET", "POST"])
  66. @login_required
  67. def myparks():
  68.     """Page with all parks"""
  69.     if request.method == "GET":
  70.         return render_template("myparks.html")
  71.  
  72. # app route to see all reviews of parks
  73. @app.route("/reviews", methods=["GET", "POST"])
  74. @login_required
  75. def reviews():
  76.     """Page with all parks"""
  77.     if request.method == "GET":
  78.         return render_template("reviews.html")
  79.  
  80.  
  81. # app route to register an account
  82. @app.route("/register", methods=["GET", "POST"])
  83. def register():
  84.     """Register user"""
  85.  
  86.     if request.method == "GET":
  87.         return render_template("register.html")
  88.  
  89.     else:
  90.         errors = ["Must provide username", "Must provide password", "Password and confirmation must match", "Username is taken"]
  91.  
  92.         if not request.form.get("username"):
  93.             return render_template("register.html", errors=errors[0])
  94.  
  95.         elif not request.form.get("password"):
  96.             return render_template("register.html", errors=errors[1])
  97.  
  98.         elif request.form.get("password") != request.form.get("confirmation"):
  99.             return render_template("register.html", errors=errors[2])
  100.  
  101.         rows = db.execute("SELECT username FROM users WHERE username = :username;",
  102.             username=request.form.get("username"))
  103.  
  104.         if len(rows) != 0:
  105.             return render_template("register.html", errors=errors[3])
  106.  
  107.     password_var = request.form.get("password")
  108.     hash_pw = generate_password_hash(password_var)
  109.     user_name = request.form.get("username")
  110.  
  111.     db.execute("INSERT INTO users(username,hash) VALUES (?,?);",
  112.         user_name, hash_pw)
  113.  
  114.     success_login = ["Registered!"]
  115.  
  116.     # select the username from our db as the current session and store it as the current users logged in session, it's the first index in the list of dicts returned
  117.     session["user_id"] = db.execute("SELECT id FROM users WHERE username = :username;",
  118.                           username=user_name) [0]["id"]
  119.  
  120.     index_park_info = send_to_index()
  121.  
  122.     return render_template("index.html", success_login=success_login[0], index_park_info=index_park_info)
  123.  
  124. @app.route("/logout")
  125. def logout():
  126.     """Log user out"""
  127.  
  128.     # Forget any user_id
  129.     session.clear()
  130.  
  131.     # Redirect user to login form
  132.     return redirect("/")
  133.  
  134. @app.route("/login", methods=["GET", "POST"])
  135. def login():
  136.     """Log user in"""
  137.  
  138.     # Forget any user_id
  139.     session.clear()
  140.  
  141.     # User reached route via POST (as by submitting a form via POST)
  142.     if request.method == "POST":
  143.  
  144.         # list of all potential errors that can be rendered on the buy html
  145.         errors = ["Must provide a username", "Must provide password", "Invalid username and/or password"]
  146.  
  147.         # Ensure username was submitted
  148.         if not request.form.get("username"):
  149.             return render_template("login.html", errors=errors[0])
  150.  
  151.         # Ensure password was submitted
  152.         elif not request.form.get("password"):
  153.             return render_template("login.html", errors=errors[1])
  154.  
  155.         # Query database for username
  156.         rows = db.execute("SELECT * FROM users WHERE username = :username",
  157.                           username=request.form.get("username"))
  158.  
  159.         # Ensure username exists and password is correct
  160.         if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
  161.             return render_template("login.html", errors=errors[2])
  162.  
  163.         # Remember which user has logged in
  164.         session["user_id"] = rows[0]["id"]
  165.  
  166.         # Redirect user to home page
  167.         return redirect("/")
  168.  
  169.     # User reached route via GET (as by clicking a link or via redirect)
  170.     else:
  171.         return render_template("login.html")
  172.  
  173. def send_to_index():
  174.  
  175.     # Query db, joining both the all_skateparks & skateparks_location tables, to grab the park info + location of a park to send to my index.html
  176.     index_park_info = db.execute("SELECT name, formatted_address, phone, website, location_lat, location_long FROM (SELECT * FROM all_skateparks JOIN skatepark_location ON all_skateparks.place_id = skatepark_location.place_id);")
  177.  
  178.     return index_park_info
Add Comment
Please, Sign In to add comment