This is currently the code that I'm using to validate and check for errors in a flask app, where the form fields are coming from a /registration html page:
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
if request.form['register'] == 'Register':
if request.form.get("eulacheck") != "on":
return regError("Please read and agree to the Terms and Conditions and the License Terms.")
if request.form['username'] == "":
return regError("Please select a username.")
if request.form['password1'] == "":
return regError("Please enter a password.")
if request.form['password2'] == "":
return regError("Please confirm password.")
if request.form['password1'] != request.form['password2']:
return regError("Passwords did not match. Please enter passwords again.")
username = request.form['username']
password = request.form['password1']
hash = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt())
id = randint(1000,9999)
if request.form['email1'] != "":
if request.form['email2'] == "":
return regError("Please confirm email.")
if request.form['email1'] != request.form['email2']:
return regError("Email addresses did not match. Please enter emails again.")
email = request.form['email1']
insert_db("INSERT INTO Users (ID, Username, Email, Hash) VALUES (?, ?, ?, ?)", (id, username, email, hash))
flash("Account registration successfull! Please use your credentials to login below.")
return render_template("login.html",pageType=['login'],flashType="info")
insert_db("INSERT INTO Users (ID, Username, Hash) VALUES (?, ?, ?)", (id, username, hash))
flash("Account registration successfull! Please use your credentials to login below.")
return render_template("login.html",pageType=['login'],flashType="info")
return render_template("register.html",pageType=['register'])
def regError(message):
flash(message)
return render_template("register.html",pageType=['register'],flashType="danger")
This code seems a bit messy and repetitive, is there a better way that I should be doing this? Thanks a lot!