EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask Users
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask Users

Flask Users

Definition of Flask Users

Flask users are defined as a module or utility that enables developers to provide customizable user authentication and user management in a Flask application as an immediate out of the box solution bringing in the capability of sessions, login pages, registration pages, emailing post-registration, emailing the confirmation links, password changing links, and similar such kinds. In other words, the module provides developers to register users, send confirmations, changing usernames or passwords, and all sorts of the login of user-related capability. This module comes in a well-documented format and can be referred to anytime it is needed. In this article, we will go through the usage of flask users in real-world projects.

Syntax:

In cases of a web applications, we generally start with a simple login page and there we would like to authenticate our users. In those cases, we would need to not only handle registrations, email confirmations, providing flexibility to change usernames or passwords but also offer added security, increased reliability, role-based authorization, and finally possibility of including international languages. Here we will look at all the syntax that is a part of the flask user in its mission to provide multiple capabilities.

Installing the Flask user module:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

pip install Flask-User
Importing all the libraries from Flask user module:
from flask_user import *
Importing login_required library from Flask user module:
from flask_user import login_required
Importing UserManager library from Flask user module:
from flask_user import UserManager
Importing UserMixin library from Flask user module:
from flask_user import UserMixin
Importing SQLAlchemyAdapter library from Flask user module:
from flask_user import SQLAlchemyAdapter

How does user function work in Flask?

In the user module, there are many sub utilities which have their respective way of working and in this section, we will learn more about those sub utilities which majorly captures the utility of flask user module. Just a point of disclaimer is that the list of modules that will be discussed here is not exhaustive, but ones that are widely used.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,328 ratings)

The first utility we will talk about is the working of login_required. This is the decorator which is used by developers to ensure that a user is logged in before accessing a page. This page can either be a rendered page or any other endpoint that needs to be accessed. Here in this utility, the class or decorator login_required extends the Flask Login’s utility of making sure that the user is logged in before accessing the page. Now, when a decorator is used, it makes the function mapped to that decorator only accessible to logged-in users. The decorator has an is_authenticated( ) implementation that provides the capability of knowing if the user is authenticated. Once the decorator is mapped to the function, any usage functionality in the function of the landing URLs will be controlled thus limiting the modification or deletion of HTTP operations to only the users for whom the utility is enabled.

The next utility that we will talk about is UserManager. This utility can be called a library from the flask_user module. This contains a UserManager class that implements most of the functionality of flask_user. Also, the features in UserManager is fully customizable which can be done by extending or overriding the methods within the class. This class would require parameters like: Flask application instance, Object-Database mapper instance, and a userClass. This utility allows developers to configure the user settings and these settings are then relayed back when any of the utilities are required. For example, if USER_ENABLE_FORGOT_PASSWORD parameter is True, then the Forgot password link will be enabled for its respective usage.

So, by now we have known about how the user is authenticated in login_required, and also supporting facilities to modify one’s settings using UserManager. Now the third is about UserMixin utility. This function allows secured storage of User ID in the browser cache and invalidates a token when there is a change in password. The details in user ID and password are encrypted, timestamped, and signed as well. The utility is extended from flask_login utility and is not a standalone utility. It stores the user ID, takes help from login_required to know if the user is authenticated and acts “like chocolate chips in a cookie” and helps build the utility of the application to what is wanted.

The final module is SQLAlchemyAdapter, and this helps in shielding itself from Database operations. Operations like finding all objects, getting objects, adding objects,s, etc. This module needs Flask-SQLAlchemy as a dependent. Calling this function, we will be able to register the user model.

Concluding, with the above classes in place it collectively works together for the utility of the entire flask_user module!

Examples

Example #1

Installing the Flask user module

Syntax:

pip install Flask-User

Output:

flask user 1

Example #2

Using abort function to portray unauthorized login

Syntax

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter
appFlask = Flask(__name__)
appFlask.config['SECRET_KEY'] = 'eduCBA'
appFlask.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://// Users/edu/database.db'
appFlask.config['CSRF_ENABLED'] = True
appFlask.config['USER_ENABLE_EMAIL'] = False
db = SQLAlchemy(appFlask)
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')
active = db.Column(db.Boolean(), nullable=False, server_default='0')
adapterDB = SQLAlchemyAdapter(db, User)
manageUser = UserManager(adapterDB, appFlask)
@appFlask.route('/')
def index():
return '<h1>This is the initial landing page!</h1>'
@appFlask.route('/profile')
@login_required
def profile():
return '<h1>This page is accessible to logged in users!</h1>'
if __name__ == '__main__':
appFlask.run(debug=True)

Output

For admin login:

flask user 2

For another user Login:

flask user 3

Conclusion

To conclude, in this article we have looked at the simple way of working for redirect function and also how to abort function goes hand in hand with the redirect function. Usage of this functionality is left to readers to try out these concepts in Flask applications. Also, the list of error codes here will come in handy for our readers to use for correct functionality!

Recommended Articles

This is a guide to Flask Users. Here we discuss the definition, How does user function work in Flask? and examples with code implementation. You may also have a look at the following articles to learn more –

  1. Flask URL Parameters
  2. Flask HTTPS
  3. Flask DB Migrate
  4. Flask Environment Variables
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more