Advertisement
DragonOsman

register route on application.py Pset7

Mar 10th, 2017
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. @app.route("/register", methods=["GET", "POST"])
  2. def register():
  3.     """Register user."""
  4.    
  5.     #forget any user_id
  6.     session.clear()
  7.    
  8.     # if user reached route via POST (as by submitting a form via POST)
  9.     if request.method == "POST":
  10.        
  11.         # ensure username was submitted
  12.         if not request.form.get("username"):
  13.             return apology("must provide username")
  14.        
  15.         #ensure password was submitted
  16.         elif not request.form.get("password"):
  17.             return apology("must provide password")
  18.        
  19.         # ensure same password was entered twice
  20.         if request.form.get("password") != request.form.get("password confirmation"):
  21.             return apology("passwords much match! (password field and password confirmation field)")
  22.        
  23.         # secure user's password: hash password with pwd_context.encrypt()
  24.         # "username" is a UNIQUE field in the database, as is the "user_id" field.
  25.         # check for db.execute failure
  26.         # try to add user to database with:
  27.         # db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
  28.         # if not result:
  29.         #    return apology("...") to print error message that the username already exists
  30.         # once they register successfully, log them in automatically
  31.         # store their id in session
  32.         #     session["user_id"]
  33.         hash = pwd_context.encrypt(request.form.get("password"))
  34.         result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
  35.         if not result:
  36.             return apology("username already exists!")
  37.        
  38.         rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
  39.         if not rows:
  40.             apology("something went wrong")
  41.         session["user_id"] = rows[0]["id"]
  42.         return render_template("register.html")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement