In this tutorial, we'll be creating a complete login and registration system with Python Flask and MySQL. Show
Python is currently taking the web development scene by storm, growing consistently every year. It has a low learning curve and therefore much easier to adapt to compared to other known languages (Node.js, PHP, etc.). In addition, Python is relatively new, so it would be advantageous to start learning immediately. The Advanced package includes additional features and a download link to the source code. 1. Getting StartedThere are a few steps we need to take before we create our python login and registration system. We need to download and set-up Python and install the packages that our app will depend on. 1.1. What You Will Learn in this Tutorial
1.2. Requirements
1.3. File Structure & SetupWe need to create our project directory and files. You can create the directory anywhere on your computer, as long as Python can access it. Create the directories and files below. File Structure \-- pythonlogin Each file will contain the following:
The below instruction will start your web server (Windows):
Debug mode will enable us to edit our files without constantly restarting the web server. 2. Creating the Database and setting-up TablesMySQL Workbench is a GUI for managing our databases. Follow the below instructions on how to get started.
The above SQL statement will create our database pythonlogin with the table accounts, along with a test account that we can use for testing purposes. 3. Creating the Stylesheet (CSS3)Edit the style.css file and add the following:
The above stylesheet will structure our pages and provide an innovative experience for our users. Feel free to customize the stylesheet (change text color, font sizes, content width, etc). 4. Creating the Login SystemWe can finally start coding with Python! What we'll do in this section is create the login template, connect to our MySQL database, implement login authentication, and define session variables. The first thing we need to do is import the packages we're going to use, edit the main.py file, and add the following:
Now that we have imported all the packages we're going to use, we need to create the MySQL and app related variables and configure the MySQL connection details. Add after:
Ensure to configure the MySQL variables to reflect your MySQL details. Now we can proceed to create the login page. To do that, we need to create a new route. Routes will enable us to associate our functions with a particular URL. Add after: 4.1 Creating the Login TemplateEdit the index.html file and add:
As you can see with the login template, we create the form along with the input fields: username and password. The form's method is set to post which determines the type of request we want to send to our server. We'll be using a POST request to send the form data. If we navigate to http://localhost:5000/pythonlogin/ in our web browser, it will look like the following: http://localhost:5000/pythonlogin/ If you click the Login button, nothing will happen or will return an error, that's because we haven't implemented the code that handles the POST request. 4.2 Authenticating Users with PythonNow we need to go back to our main.py file and add the authentication code to our route function that we created. After:
Add:
With the code above, we use an if statement to check if the requested method is POST and check if the username and password variables exist in the form request. If they both exist, the username and password variables will be created, which will be associated with the form variables. Add after:
The code above will execute a SQL query that will retrieve the account details from our accounts table in our MySQL database. The username and password variables are associated with this query as that is what we will use to find the account. Add after:
The code above will determine if the account exists. If it does, the session variables are declared. These session variables will be remembered for the user as they will be used to determine whether the user is logged-in or not. Session variables basically act like browser cookies. They are stored on the server as opposed to the user's browser. If the account doesn't exist, we can simply output the error on the login form. Your login route should look like the following:
To make sure everything is working correctly, navigate to http://localhost:5000/pythonlogin/ and input "test" in both the username and password fields, and then click the Login button. You should receive a message that outputs "Logged in successfully!". 4.3 Creating the Logout ScriptFor a user to logout, all we have to do is remove the session variables that were created when the user logged-in. Add the following code to the main.py file:
The above code will remove each session variable associated with the user. Without these session variables, the user cannot be logged-in. Subsequently, the user is redirected to the login page. We can logout by navigating to the following URL: http://localhost:5000/pythonlogin/logout 5. Creating the Registration SystemWe need a registration system that users can use to register on our app. What we'll do in this section is to create a new register route and create the registration template, along with the registration form, which will consist of input fields, submit button, etc. 5.1 Creating the Registration TemplateEdit the register.html file and add:
The HTML template above we'll use to register users. It's identical to the login template but also includes the Email input field. The form's action attribute is associated with the "register" route, as we'll use this route to handle the POST request. 5.2 Registering Users with PythonNow that we have our template created, we can proceed to create the "register" route, which will handle the POST request and insert a new account into our accounts table, but only if the submitted fields are valid. Go back to the main.py file and add the following:
We create the "register" route and implement validation that will check if all the form fields exist. If they don't, then output a simple error. After:
Add:
The above code will select an account with the submitted username and password fields. If the account doesn't exist, we can proceed to validate the input data. Validation will check if the submitted email is valid and check if the username contains only letters and numbers. Subsequently, the code will insert a new account into our accounts tables. To test that it is working correctly, navigate to http://localhost:5000/pythonlogin/register and fill out the form and click the Register button. You should receive the following response: http://localhost:5000/pythonlogin/register Now we can go back to our index.html file and change this line:
To:
Users can now register and log in to our app. Next, we'll create a basic home page for logged-in users. 6. Creating the Home PageThe home page will be restricted to logged-in users only. Non-registered users cannot access this page. You can adapt this page and create more pages. Edit the main.py file and add the following:
The above code will create the home route function. If the user is logged-in, they will have access to the home page. If not, they will be redirected to the login page. Edit the home.html file and add the following:
We also need to create the layout for our logged-in pages. Edit the layout.html file and add:
Now we can easily extend the same layout for both the home and profile pages. Currently, when a user logs in, there will be a basic output message, we can now change that to redirect the user to our new home page instead. Find the following code in the login route function:
Replace with:
The user will now be redirected to the home page when they log in. If we enter the test details into the login form and click the Login button, we will see the following: http://localhost:5000/pythonlogin/home It's just a simple home page that will output the username. You can implement your own code later. Next, we'll create the profile page and populate the user's details. 7. Creating the Profile PageThe profile page will populate all details associated with the account (username, password, and email). Add the following route to the main.py file:
The above code will create the profile route and retrieve all the account details from the database, but only if the user is logged-in. Edit the profile.html file and add:
The above code will extend the layout (layout.html) file that we created previously. If you navigate to the profile page, it will look like the following: http://localhost:5000/pythonlogin/profile That's basically it for the home and profile pages. The Advanced package includes the edit profile feature that will enable the user to change their username, password, and email. ConclusionCongratulations! You've successfully created your own login and registration system with Python Flask and MySQL. You're free to use the source code from this tutorial in your application(s). If you enjoyed this tutorial, don't forget to hit the share button and drop a comment as it will help us create more future content. If you would like to support us, consider purchasing a package below as it will greatly help us create more quality tutorials and keep our server up and running. BasicAdvancedSource code Database SQL file Login & Registration system Home page Profile page Activate account feature Edit profile page Remember me feature AJAX integration Password encryption Forgot & Reset Password CSRF Protection Brute-force Protection reCAPTCHA Protection Two-factor Authentication Activation Email Template Admin Panel Responsive Design (mobile-friendly) SCSS file Commented code Free updates & support (bugs and minor issues) User Guide * Payments are processed with PayPal/Stripe. For more detailed information regarding the advanced package, click here. |