Flask Registration Code Tutorial




In this tutorial, we're going to work some more on our registration code within the __init__.py.

Before we go any further, let's install passlib with:

pip install passlib

Then, adding some imports to our __init__.py file:

	  
from flask import Flask, render_template, flash, request, url_for, redirect, session
from wtforms import Form, BooleanField, TextField, PasswordField, validators
from passlib.hash import sha256_crypt
from MySQLdb import escape_string as thwart
import gc
	  

Passlib will be used for password encryption, and the escape_string is used to protect against SQL injection attempts (hacking). The gc module is used for garbage collection (memory issues). We also add session to the flask imports, which is used for accessing the user-specific session / cookie information. We also import a bunch of the field stuff from wtforms.

Now we have some new register_page function code:

@app.route('/register/', methods=["GET","POST"])
def register_page():
    try:
        form = RegistrationForm(request.form)

        if request.method == "POST" and form.validate():
            username  = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))
            c, conn = connection()

            x = c.execute("SELECT * FROM users WHERE username = (%s)",
                          (thwart(username)))

            if int(x) > 0:
                flash("That username is already taken, please choose another")
                return render_template('register.html', form=form)

            else:
                c.execute("INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)",
                          (thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming/")))
                
                conn.commit()
                flash("Thanks for registering!")
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username

                return redirect(url_for('dashboard'))

        return render_template("register.html", form=form)

    except Exception as e:
        return(str(e))
		

There's a lot going on here. If you would like an in-depth walkthrough of this code, see the video.

Simple, the code first will check to see if the method is a POST. Keep in mind, the user might just be simply loading the register page. If there is a POST request, then we want to gather the information in the form.

Once we have the information in the form, the next thing we want to do is connect to the database. Now we don't want to have two users with the same username, so we first want to see if that username already exists. If it does, then we want to tell them that username already exists, and let them try again.

If the username does not already exist, and we've made it to this point, that means we have a unique username, passwords that match, and an email, ready to insert into our database.

So we insert to the database, flash a message to the user thanking them to register, and you're done.

When you're all set with your insertions, then you need to make sure you always run a conn.commit(), which is "save" your changes to the database. If you forget to do this, then your changes will not be saved.

Finally, we use gc.collect() to help keep memory waste down.

Notice also that we happen to log in our user after they register, using the flask session functionality.

The next tutorial:





  • Introduction to Practical Flask
  • Basic Flask Website tutorial
  • Flask with Bootstrap and Jinja Templating
  • Starting our Website home page with Flask Tutorial
  • Improving the Home Page Flask Tutorial
  • Finishing the Home Page Flask Tutorial
  • Dynamic User Dashboard Flask Tutorial
  • Content Management Beginnings Flask Tutorial
  • Error Handling with Flask Tutorial
  • Flask Flash function Tutorial
  • Users with Flask intro Tutorial
  • Handling POST and GET Requests with Flask Tutorial
  • Creating MySQL database and table Flask Tutorial
  • Connecting to MySQL database with MySQLdb Flask Tutorial
  • User Registration Form Flask Tutorial
  • Flask Registration Code Tutorial
  • Finishing User Registration Flask Tutorial
  • Password Hashing with Flask Tutorial
  • Flask User Login System Tutorial
  • Decorators - Login_Required pages Flask Tutorial
  • Dynamic user-based content Flask Tutorial
  • More on Content Management Flask Tutorial
  • Flask CMS Concluded Flask Tutorial
  • The Crontab Flask Tutorial
  • Flask SEO Tutorial
  • Flask Includes Tutorial
  • Jinja Templating Tutorial
  • Flask URL Converters Tutorial
  • Flask-Mail Tutorial for email with Flask
  • Return Files with Flask send_file Tutorial
  • Protected Directories with Flask Tutorial
  • jQuery with Flask Tutorial
  • Pygal SVG graphs with Flask Tutorial
  • PayPal with Flask Web Development Tutorial
  • Securing your Flask website with SSL for HTTPS using Lets Encrypt