The Flask Mega-Tutorial Part V: User Logins

Posted by
on under

This is the fifth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to create a user login subsystem.

For your reference, below is a list of the articles in this series.

In Chapter 3 you learned how to create the user login form, and in Chapter 4 you learned how to work with a database. This chapter will teach you how to combine the topics from those two chapters to create a simple user login system.

The GitHub links for this chapter are: Browse, Zip, Diff.

Password Hashing

In Chapter 4 the user model was given a password_hash field, that so far is unused. The purpose of this field is to hold a hash of the user password, which will be used to verify the password entered by the user during the log in process. Password hashing is a complicated topic that should be left to security experts, but there are several easy to use libraries that implement all that logic in a way that is simple to be invoked from an application.

One of the packages that implement password hashing is Werkzeug, which you may have seen referenced in the output of pip when you install Flask, since it is one of its core dependencies. Since it is a dependency, Werkzeug is already installed in your virtual environment. The following Python shell session demonstrates how to hash a password:

>>> from import generate_password_hash
>>> hash = generate_password_hash('foobar')
>>> hash

In this example, the password foobar is transformed into a long encoded string through a series of cryptographic operations that have no known reverse operation, which means that a person that obtains the hashed password will be unable to use it to obtain the original password. As an additional measure, if you hash the same password multiple times, you will get different results, so this makes it impossible to identify if two users have the same password by looking at their hashes.

The verification process is done with a second function from Werkzeug, as follows:

>>> from import check_password_hash
>>> check_password_hash(hash, 'foobar')
>>> check_password_hash(hash, 'barfoo')

The verification function takes a password hash that was previously generated, and a password entered by the user at the time of log in. The function returns True if the password provided by the user matches the hash, or False otherwise.

The whole password hashing logic can be implemented as two new methods in the user model:

app/ Password hashing and verification

from import generate_password_hash, check_password_hash

# ...

class User(db.Model):
    # ...

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

With these two methods in place, a user object is now able to do secure password verification, without the need to ever store original passwords. Here is an example usage of these new methods:

>>> u = User(username='susan', email='')
>>> u.set_password('mypassword')
>>> u.check_password('anotherpassword')
>>> u.check_password('mypassword')

Introduction to Flask-Login

In this chapter I'm going to introduce you to a very popular Flask extension called Flask-Login. This extension manages the user logged-in state, so that for example users can log in to the application and then navigate to different pages while the application "remembers" that the user is logged in. It also provides the "remember me" functionality that allows users to remain logged in even after closing the browser window. To be ready for this chapter, you can start by installing Flask-Login in your virtual environment:

(venv) $ pip install flask-login

As with other extensions, Flask-Login needs to be created and initialized right after the application instance in app/ This is how this extension is initialized:

app/ Flask-Login initialization

# ...
from flask_login import LoginManager

app = Flask(__name__)
# ...
login = LoginManager(app)

# ...

Preparing The User Model for Flask-Login

The Flask-Login extension works with the application's user model, and expects certain properties and methods to be implemented in it. This approach is nice, because as long as these required items are added to the model, Flask-Login does not have any other requirements, so for example, it can work with user models that are based on any database system.

The four required items are listed below:

  • is_authenticated: a property that is True if the user has valid credentials or False otherwise.
  • is_active: a property that is True if the user's account is active or False otherwise.
  • is_anonymous: a property that is False for regular users, and True for a special, anonymous user.
  • get_id(): a method that returns a unique identifier for the user as a string (unicode, if using Python 2).

I can implement these four easily, but since the implementations are fairly generic, Flask-Login provides a mixin class called UserMixin that includes generic implementations that are appropriate for most user model classes. Here is how the mixin class is added to the model:

app/ Flask-Login user mixin class

# ...
from flask_login import UserMixin

class User(UserMixin, db.Model):
    # ...

User Loader Function

Flask-Login keeps track of the logged in user by storing its unique identifier in Flask's user session, a storage space assigned to each user who connects to the application. Each time the logged-in user navigates to a new page, Flask-Login retrieves the ID of the user from the session, and then loads that user into memory.

Because Flask-Login knows nothing about databases, it needs the application's help in loading a user. For that reason, the extension expects that the application will configure a user loader function, that can be called to load a user given the ID. This function can be added in the app/ module:

app/ Flask-Login user loader function

from app import login
# ...

def load_user(id):
    return User.query.get(int(id))

The user loader is registered with Flask-Login with the @login.user_loader decorator. The id that Flask-Login passes to the function as an argument is going to be a string, so databases that use numeric IDs need to convert the string to integer as you see above.

Logging Users In

Let's revisit the login view function, which as you recall, implemented a fake login that just issued a flash() message. Now that the application has access to a user database and knows how to generate and verify password hashes, this view function can be completed.

app/ Login view function logic

# ...
from flask_login import current_user, login_user
from app.models import User

# ...

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
        if user is None or not user.check_password(
            flash('Invalid username or password')
            return redirect(url_for('login'))
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

The top two lines in the login() function deal with a weird situation. Imagine you have a user that is logged in, and the user navigates to the /login URL of your application. Clearly that is a mistake, so I want to not allow that. The current_user variable comes from Flask-Login and can be used at any time during the handling to obtain the user object that represents the client of the request. The value of this variable can be a user object from the database (which Flask-Login reads through the user loader callback I provided above), or a special anonymous user object if the user did not log in yet. Remember those properties that Flask-Login required in the user object? One of those was is_authenticated, which comes in handy to check if the user is logged in or not. When the user is already logged in, I just redirect to the index page.

In place of the flash() call that I used earlier, now I can log the user in for real. The first step is to load the user from the database. The username came with the form submission, so I can query the database with that to find the user. For this purpose I'm using the filter_by() method of the SQLAlchemy query object. The result of filter_by() is a query that only includes the objects that have a matching username. Since I know there is only going to be one or zero results, I complete the query by calling first(), which will return the user object if it exists, or None if it does not. In Chapter 4 you have seen that when you call the all() method in a query, the query executes and you get a list of all the results that match that query. The first() method is another commonly used way to execute a query, when you only need to have one result.

If I got a match for the username that was provided, I can next check if the password that also came with the form is valid. This is done by invoking the check_password() method I defined above. This will take the password hash stored with the user and determine if the password entered in the form matches the hash or not. So now I have two possible error conditions: the username can be invalid, or the password can be incorrect for the user. In either of those cases, I flash an message, and redirect back to the login prompt so that the user can try again.

If the username and password are both correct, then I call the login_user() function, which comes from Flask-Login. This function will register the user as logged in, so that means that any future pages the user navigates to will have the current_user variable set to that user.

To complete the login process, I just redirect the newly logged-in user to the index page.

Logging Users Out

I know I will also need to offer users the option to log out of the application. This can be done with Flask-Login's logout_user() function. Here is the logout view function:

app/ Logout view function

# ...
from flask_login import logout_user

# ...

def logout():
    return redirect(url_for('index'))

To expose this link to users, I can make the Login link in the navigation bar automatically switch to a Logout link after the user logs in. This can be done with a conditional in the base.html template:

app/templates/base.html: Conditional login and logout links

        <a href="{{ url_for('index') }}">Home</a>
        {% if current_user.is_anonymous %}
        <a href="{{ url_for('login') }}">Login</a>
        {% else %}
        <a href="{{ url_for('logout') }}">Logout</a>
        {% endif %}

The is_anonymous property is one of the attributes that Flask-Login adds to user objects through the UserMixin class. The current_user.is_anonymous expression is going to be True only when the user is not logged in.

Requiring Users To Login

Flask-Login provides a very useful feature that forces users to log in before they can view certain pages of the application. If a user who is not logged in tries to view a protected page, Flask-Login will automatically redirect the user to the login form, and only redirect back to the page the user wanted to view after the login process is complete.

For this feature to be implemented, Flask-Login needs to know what is the view function that handles logins. This can be added in app/

# ...
login = LoginManager(app)
login.login_view = 'login'

The 'login' value above is the function (or endpoint) name for the login view. In other words, the name you would use in a url_for() call to get the URL.

The way Flask-Login protects a view function against anonymous users is with a decorator called @login_required. When you add this decorator to a view function below the @app.route decorators from Flask, the function becomes protected and will not allow access to users that are not authenticated. Here is how the decorator can be applied to the index view function of the application:

app/ @login\_required decorator

from flask_login import login_required

def index():
    # ...

What remains is to implement the redirect back from the successful login to the page the user wanted to access. When a user that is not logged in accesses a view function protected with the @login_required decorator, the decorator is going to redirect to the login page, but it is going to include some extra information in this redirect so that the application can then return to the first page. If the user navigates to /index, for example, the @login_required decorator will intercept the request and respond with a redirect to /login, but it will add a query string argument to this URL, making the complete redirect URL /login?next=/index. The next query string argument is set to the original URL, so the application can use that to redirect back after login.

Here is a snippet of code that shows how to read and process the next query string argument:

app/ Redirect to "next" page

from flask import request
from werkzeug.urls import url_parse

@app.route('/login', methods=['GET', 'POST'])
def login():
    # ...
    if form.validate_on_submit():
        user = User.query.filter_by(
        if user is None or not user.check_password(
            flash('Invalid username or password')
            return redirect(url_for('login'))
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    # ...

Right after the user is logged in by calling Flask-Login's login_user() function, the value of the next query string argument is obtained. Flask provides a request variable that contains all the information that the client sent with the request. In particular, the request.args attribute exposes the contents of the query string in a friendly dictionary format. There are actually three possible cases that need to be considered to determine where to redirect after a successful login:

  • If the login URL does not have a next argument, then the user is redirected to the index page.
  • If the login URL includes a next argument that is set to a relative path (or in other words, a URL without the domain portion), then the user is redirected to that URL.
  • If the login URL includes a next argument that is set to a full URL that includes a domain name, then the user is redirected to the index page.

The first and second cases are self-explanatory. The third case is in place to make the application more secure. An attacker could insert a URL to a malicious site in the next argument, so the application only redirects when the URL is relative, which ensures that the redirect stays within the same site as the application. To determine if the URL is relative or absolute, I parse it with Werkzeug's url_parse() function and then check if the netloc component is set or not.

Showing The Logged In User in Templates

Do you recall that way back in Chapter 2 I created a fake user to help me design the home page of the application before the user subsystem was in place? Well, the application has real users now, so I can now remove the fake user and start working with real users. Instead of the fake user I can use Flask-Login's current_user in the template:

app/templates/index.html: Pass current user to template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}

And I can remove the user template argument in the view function:

app/ Do not pass user to template anymore

def index():
    # ...
    return render_template("index.html", title='Home Page', posts=posts)

This is a good time to test how the login and logout functionality works. Since there is still no user registration, the only way to add a user to the database is to do it via the Python shell, so run flask shell and enter the following commands to register a user:

>>> u = User(username='susan', email='')
>>> u.set_password('cat')
>>> db.session.add(u)
>>> db.session.commit()

If you start the application and go to the application's / or /index URLs, you will be immediately redirected to the login page, and after you log in using the credentials of the user that you added to your database, you will be returned to the original page, in which you will see a personalized greeting.

User Registration

The last piece of functionality that I'm going to build in this chapter is a registration form, so that users can register themselves through a web form. Let's begin by creating the web form class in app/

app/ User registration form

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User

# ...

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(
        if user is not None:
            raise ValidationError('Please use a different email address.')

There are a couple of interesting things in this new form related to validation. First, for the email field I've added a second validator after DataRequired, called Email. This is another stock validator that comes with WTForms that will ensure that what the user types in this field matches the structure of an email address.

The Email() validator from WTForms requires an external dependency to be installed:

(venv) $ pip install email-validator

Since this is a registration form, it is customary to ask the user to type the password two times to reduce the risk of a typo. For that reason I have password and password2 fields. The second password field uses yet another stock validator called EqualTo, which will make sure that its value is identical to the one for the first password field.

When you add any methods that match the pattern validate_<field_name>, WTForms takes those as custom validators and invokes them in addition to the stock validators. I have added two of those methods to this class for the username and email fields. In this case I want to make sure that the username and email address entered by the user are not already in the database, so these two methods issue database queries expecting there will be no results. In the event a result exists, a validation error is triggered by raising an exception of type ValidationError. The message included as the argument in the exception will be the message that will be displayed next to the field for the user to see.

To display this form on a web page, I need to have an HTML template, which I'm going to store in file app/templates/register.html. This template is constructed similarly to the one for the login form:

app/templates/register.html: Registration template

{% extends "base.html" %}

{% block content %}
    <form action="" method="post">
        {{ form.hidden_tag() }}
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ }}<br>
            {{ }}<br>
            {% for error in %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.password2.label }}<br>
            {{ form.password2(size=32) }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        <p>{{ form.submit() }}</p>
{% endblock %}

The login form template needs a link that sends new users to the registration form, right below the form:

app/templates/login.html: Link to registration page

    <p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p>

And finally, I need to write the view function that is going to handle user registrations in app/

app/ User registration view function

from app import db
from app.forms import RegistrationForm

# ...

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(,
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

And this view function should also be mostly self-explanatory. I first make sure the user that invokes this route is not logged in. The form is handled in the same way as the one for logging in. The logic that is done inside the if validate_on_submit() conditional creates a new user with the username, email and password provided, writes it to the database, and then redirects to the login prompt so that the user can log in.

Registration Form

With these changes, users should be able to create accounts on this application, and log in and out. Make sure you try all the validation features I've added in the registration form to better understand how they work. I am going to revisit the user authentication subsystem in a future chapter to add additional functionality such as to allow the user to reset the password if forgotten. But for now, this is enough to continue building other areas of the application.

Become a Patron!

Hello, and thank you for visiting my blog! If you enjoyed this article, please consider supporting my work on this blog on Patreon!

  • #551 Miguel Grinberg said

    @Loch: did you set a secret key in the configuration? Go back to Chapter 3 if you missed that.

  • #552 Stuart said

    This is an incredible resource, thank you so much for creating it!

    While working through this chapter, I noticed when I tested the validation that I was not getting the bracketed red spans, but rather a dialogue box popped up telling me to put data in the field. I was able to fix this by putting novalidate in the <form> tag of registration.html, just like in login.html

    I was curious if the exclusion of that tag here and in the repo is an oversight, or was it deliberate?

    Forgive me if this has been discussed elsewhere...a cmd+f for "novalidate" in the comments came back empty.

  • #553 Miguel Grinberg said

    @Stuart: the novalidate attribute was used in the first form just so that you can see the server-side validation. If you prefer to work with only server-side validation then you should add novalidate to all your forms. But really there is no reason to disable the browser validation, other than to confirm that the server is also validating. The best setup in my opinion is to validate on both sides.

  • #554 Hamid Allaoui said

    Thanks again for this new great tutorial

  • #555 AbuAkram said

    Hi Miguel... No matter how much I surf the internet for information on flask, I keep coming back to your tutorials. Keep up your good work...
    I want to secure the passwords and thought of a method, and would love to hear your opinion... Databases can be hacked and hence passwords get exposed... What if whenever a user wants to log in, a random phase is computed and exposed on the login page asking the user to add this phase at the end of his password...
    So for example if the password is 'cat' and the generated phase is 123, he has to type in cat123... which of course creates a new hash every time the user wants to log in... so even if his password is exposed, it want help much since a new hash is created at each login...
    Since I am not an expert in hacking I would love to hear from you your opinion...
    thanks in advance

  • #556 Miguel Grinberg said

    @AbuAkram: first of all, if the database is hacked, the attacker will only be able to retrieve password hashes, which cannot be used to log in. So you are incorrect saying that a database hack would give attackers access.

    Second, this "phase" number assigned to each user will have to be stored somewhere, so it will also go in the database, right? So I don't see how it increases security since it is going to be accessible to this potential attacker if it hacks the database.

  • #557 Abuakram said

    @Miguel: Thanks for your reply...
    Yes your right... Hashed passwords can't be retrieved...
    No... the computed phase is not stored in the database... It is computed at the login request and cached for a few minutes... then the new hash is computed (password + randomphase) which has to be equal to the password input of the user...

    I don't know if above detailed what is in my mind... If you don't mind I might implement it and send you the code...

  • #558 Miguel Grinberg said

    @Abuakram: I don't understand how this makes the system more secure. Let's say that an attacker hacks your database, and event though this is extremely unlikely, let's assume they are able to derive the actual passwords from the hashes stored in the database. The attacker now has the password, so they can go to your login page, get the phase (which you indicated is displayed in the login page) and log in by entering the hacked password followed by the phase.

  • #559 Bojan said

    I am confused by this statement:
    "As an additional measure, if you hash the same password multiple times, you will get different results, so this makes it impossible to identify if two users have the same password by looking at their hashes."

    How would then this work when comparing the entered password with the saved hash?
    I thought hash can always be reproduced on the same input?

  • #560 Miguel Grinberg said

    @Bojan: The hashing function provides the same output every time, but normally you add a cryptographic salt to the password before it is hashed, so two users with the same passwords will have a different hash because the salt is different. See for an explanation on salts.

  • #561 Personne said

    Just staring of the Tutorial, and I'm having an issue at the end of Chapter 5 (

    Installed version:
    (venv) [peter@centos71 tuto1]$ flask --version
    Python 3.6.8
    Flask 2.0.2
    Werkzeug 2.0.2

    Here is the error, I get: - - [05/Dec/2021 21:58:27] "GET / HTTP/1.1" 500 -
    [2021-12-05 21:58:29,096] ERROR in app: Exception on / [GET]
    Traceback (most recent call last):
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask/", line 2073, in wsgi_app
    response = self.full_dispatch_request()
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask/", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask/", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask/", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask_login/", line 270, in decorated_view
    elif not current_user.is_authenticated:
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/werkzeug/", line 432, in get
    obj = instance._get_current_object()
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/werkzeug/", line 554, in _get_current_object
    return self.__local() # type: ignore
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask_login/", line 26, in <lambda>
    current_user = LocalProxy(lambda: _get_user())
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask_login/", line 346, in _get_user
    File "/home/peter/lego/venv/lib64/python3.6/site-packages/flask_login/", line 303, in _load_user
    "Missing user_loader or request_loader. Refer to "
    Exception: Missing user_loader or request_loader. Refer to for more info.

    On the website I got this error:
    Internal Server Error
    The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

  • #562 Miguel Grinberg said

    @Personne: the error is pretty clear: "Missing user_loader or request_loader." Go back to the user loader section in this article and review your work. Or download the code from the GitHub link provided in the introduction section and compare against your code.

  • #563 MF said

    @Miguel, great tutorial. One question- why is password validation in the route, rather than as a custom validator in the form? Validation logic lives in two different places

  • #564 Miguel Grinberg said

    @MF: You are welcome to move this logic to the form if you like it better there. My opinion is that the auth logic is not form validation.

  • #565 AR said

    Hi Miguel,

    How secure the authentical and user managment disucssed in this chapter is? Say when I have to select between using google authentication out of the box or the routes mentioned here.

  • #566 Miguel Grinberg said

    @AR: You are not comparing apples to apples here. Google auth will just allow you to verify a user's identity. You still need user management, fairly similar to what's shown here to maintain the logged in state in your application. So even if you switch to Google auth, you will need a good part of what's shown here, or something similar in features. If you want to know about using Google auth vs. using hashed passwords, both are fairly secure, really hard to tell if Google surpasses a properly hashed password in terms of security.

  • #567 bhong2002 said

    hi,, good day .. I am new in python .. have an issue in check_password_hash that occurs Missing required parameter 'digestmod' ..

    def verify_password(self, password):
    return check_password_hash(self.password_hash, password)

    TypeError: Missing required parameter 'digestmod'.

    thanks :)

  • #568 Miguel Grinberg said

    @bhong2002: please post the complete stack trace of the error.

  • #569 Juraj Kovac said

    Hi Miguel

    Do you have experience with LDAP (Active Directory) logins for multiple domains in one app ?.. i mean, i run login for one AD domain using flask-ldap and it works fine, but what if i have users from multiple different AD domains, instead of creating users in this one domain which works fine i would like to let users to login to app with their existing accounts from different AD domains
    Thx a lot

  • #570 Miguel Grinberg said

    @Juraj: you should ask the developer of the extension that you are using about this. I don't really know, sorry.

  • #571 Vladimir Bankovic said

    Hey Miguel Great tutorial, learning a lot!

    However, when finished 5th Chapter, I constantly receive this error:

    sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.password_hash
    [SQL: SELECT AS user_id, user.username AS user_username, AS user_email, user.password_hash AS user_password_hash
    FROM user
    WHERE user.username = ?
    [parameters: ('vlajko', 1, 0)]
    (Background on this error at:

    I have checked the code and there is password_hash column in the User model, not sure why it is not finding it. Any guidance is appreciated!


  • #572 Miguel Grinberg said

    @Vladimir: the error is not about the code, the issue is with your database which does not have this column. You must have missed step when doing the database migration that adds this column.

  • #573 Jorge said

    Hi Miguel!

    Awesome book!
    I'm having this error, but refreshing the page shows the content. Any thoughts?
    /microblog/app/", line 37, in login
    next_page = request.args.get('next')
    NameError: name 'request' is not defined

  • #574 Miguel Grinberg said

    @Jorge: you have to import request:

    from flask import request
  • #575 Chresten said

    Hi Migeul, great stuff. Thank you!

    I encountered an issue with Werkzeug v2.1.0+ which makes flask_login imports fail. My error message is:

    ModuleNotFoundError: No module named 'flask_login'

    I have confirmed that Flask_Login is installed via pip freeze - I've tried to uninstall/reinstall and running my project with and without venv

    I believe I found the source of the error by creating an empty file and only importing flask_login. The error output is:

    from import safe_str_cmp
    ImportError: cannot import name 'safe_str_cmp' from ''

    Apparently <safe_str_cmp> has been depreciated in Werkzeug 2.1.0 per Werkzeug's release docs.

    I was able to resolve the issue by installing a previous version of Werkzug via pip:
    $ pip install Werkzeug==2.0.3

    Any idea if this issue is known wider and resolved in any other way? Or perhaps I overlooked something locally? Thanks for all your wonderful teaching!

Leave a Comment