Chapter 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy
User-based and customer-oriented are super popular in nowadays’ business model. Apart from web 2.0, web 3.0 more emphasizes decentralisation and gives back more data authority and data management to current users. So an user-centralization approach trend is arising and it just would be more important. So regarding buidling an application using Flask, user login and authentication system is a basic function it must have. Today is on how to leverage Flask login manager and build one in your application.
User-based and customer-oriented are super popular in nowadays’ business model. Apart from web 2.0, web 3.0 emphasizes decentralization and gives back more data authority and data management to current users. So a user-centralization approach trend is arising and it just would be more important. So regarding building an application using Flask, a user login and authentication system is a basic function it must have. Today is on how to leverage Flask login manager and build one in your application.
Table of Contents: Flask Login System
- Flask Login Manager Installation and Configuration
- Create and Configure the User Database using SQLAlchemy and Flask login UserMixin
- User Registration
- Flask login_user, logout_user and current_user
- Login_required decorator
- Full Python Script of Flask User Account Login and Authentication
- FAQ
Flask Login Manager Installation and Configuration
This module provides user session management in the Flask application. It handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.
Basically, the Flask login manager can let you do these things below:
- Store the active user’s ID in the session, and let you log them in and out easily.
- Let you restrict views to logged-in (or logged-out) users.
- Handle the normally tricky “remember me” functionality.
- Help protect your users’ sessions from being stolen by cookie thieves.
- Possibly integrate with Flask-Principal or other authorization extensions.
First thing first, installing a flask login manager is super easy. We can input pip3 install flask-login
into your computer terminal. Then, configuring the flask login with your flask application is by doing the three steps:
1. Import the flask login modules
2. Initiate the LoginManager instance and connect with your app
3. Define the load_user function by returning the user_id
Create and Configure the User Database using SQLAlchemy and Flask login UserMixin
No.1, we need to import the SQLAlchemy module and configure it with the flask application
Second, create a class User which is added the data column needed and the specification of each data column.
Last but not least, we need to create an initiative SQLAlchemy database. In the terminal, we can create the initiative SQLAlchemy database. Please use the application name you created in the flask application and the variable name you used to connect with the flask app. I use the app and db here.
User Registration
Now ingredients are ready to start building a registration route for new users to join your application.
First things first, a route is indispensable for users to register.
@app.route("/registration", methods=['GET', 'POST'])
For more details regarding the Flask route and collecting submission data from HTML, please check out this article
Second, by referring to the User class we created earlier, we need to match the new user input data from the form on the registration route with our database column. If your application also has an API program, here also needs to add the token variable and decode it the password input by the new user.
new_user = User(email=email, username=username, password=generate_password_hash(password, method='sha256'), token=token.decode())
Then, we can add the new_user and utilize commit()
it to confirm it, and remember it by using the login_user function we created earlier.
For more details about Flask JWT API deployment, please refer to this article
https://www.easy2digital.com/automation/data/python-tutorial-54-utilize-flask-jwt-to-tokenizer-the-api-user-identity-and-authenticate-users/
Flask login_user, logout_user, and current_user
After new user creation, Flask provides modules to facilitate developers to build up login pages, login out pages,s and detect the logged user on sites.
First thing first, we need to import the modules from the flask_login. I’ll talk about login_required in the next section.
Login_user
To verify the user login information input on the login page, we can check if the user password in the SQLAlchemy data can match the password input by the visitor.
Using the query.filter_by
in the User class to match the email address first.
Then, if the fetched email user’s password is matching the input value from the form, it’s logged in. And login_user can remember this user in any session later on before log_out.
Logout_user
Creating a new route for users to log out of their accounts
Current_user
This is a super useful module as it tells the application who is visiting the page. If you like to offer exclusive content for members or differentiate content between unknown users and sign-up users. This module facilitates you to deploy and build the functions.
return render_template("shopify.html", user=current_user)
To detect the existing users, we need to add the current_user in the render_template of each route or the routes you wanna show personalized content in the Flask application.
Login_required decorator
For any routes that are only open to members, you need to add the login_required decorator under the route. Take the logout route, for example, if a user hasn’t login yet, she or he can’t click through the logout page, and you can add a flask message to notify them login first.
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
Full Python Script of Flask Login and Authentication
If you are interested in the full python scripts of Chapter 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy, please subscribe to our newsletter by adding the message “Chapter 57”. We would send you the script immediately to your mailbox.
I hope you enjoy reading Chapter 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy. If you did, please support us by doing one of the things listed below, because it always helps out our channel.
- Support and donate to our channel through PayPal (paypal.me/Easy2digital)
- Subscribe to my channel and turn on the notification bell Easy2Digital Youtube channel.
- Follow and like my page Easy2Digital Facebook page
- Share the article on your social network with the hashtag #easy2digital
- Buy products with Easy2Digital 10% OFF Discount code (Easy2DigitalNewBuyers2021)
- You sign up for our weekly newsletter to receive Easy2Digital latest articles, videos, and discount codes
- Subscribe to our monthly membership through Patreon to enjoy exclusive benefits (www.patreon.com/louisludigital)
FAQ:
Q1: What is Flask SQLAlchemy?
A: Flask SQLAlchemy is a Python library that combines the simplicity of Flask with the power of SQLAlchemy, a popular Object-Relational Mapping (ORM) tool. It allows developers to easily interact with databases using Python code.
Q2: What are the advantages of using Flask SQLAlchemy?
A: Flask SQLAlchemy offers several advantages. Firstly, it provides a high-level interface for working with databases, simplifying the process of CRUD operations. Additionally, it supports multiple database backends, making it versatile. It also integrates well with Flask, allowing seamless integration with web applications.
Q3: How do I install Flask SQLAlchemy?
A: To install Flask SQLAlchemy, you can use pip, the Python package installer. Simply run the command ‘pip install Flask-SQLAlchemy’ in your terminal or command prompt.
Q4: Can Flask SQLAlchemy be used with any database?
A: Yes, Flask SQLAlchemy supports multiple database backends, including popular options like SQLite, MySQL, PostgreSQL, and Oracle. This flexibility allows you to use the database that best suits your needs.
Q5: Is Flask SQLAlchemy suitable for large-scale applications?
A: Yes, Flask SQLAlchemy is suitable for large-scale applications. It is designed to handle complex database operations efficiently and offers features like connection pooling and query optimization. However, it’s important to properly optimize your code and database queries to ensure optimal performance.
Q6: Does Flask SQLAlchemy support migration?
A: Yes, Flask SQLAlchemy provides migration support through the Alembic library. Alembic allows you to easily manage database schema changes and apply them to your production database without data loss.
Q7: Is Flask SQLAlchemy compatible with Flask extensions?
A: Yes, Flask SQLAlchemy is compatible with various Flask extensions. It integrates seamlessly with Flask-WTF for form handling, Flask-Login for user authentication, and Flask-Admin for admin interfaces, among others.
Q8: Can Flask SQLAlchemy handle complex queries?
A: Yes, Flask SQLAlchemy provides a powerful query API that allows you to construct complex queries using Python code. It supports filtering, sorting, joining multiple tables, and aggregating data.
Q9: Is Flask SQLAlchemy suitable for beginners?
A: Flask SQLAlchemy can be used by beginners, but it does require some understanding of SQL and database concepts. It is recommended to have a basic understanding of Python and databases before diving into Flask SQLAlchemy.
Q10: Are there any alternatives to Flask SQLAlchemy?
A: Yes, there are alternative ORM libraries available for Flask, such as Pony ORM and Peewee. However, Flask SQLAlchemy is widely used and well-documented, making it a popular choice for many developers.
python tutorial 56