[Flask] Stuck with @login_required which breaks our app

Stefan Knecht knecht.stefan at gmail.com
Thu Feb 24 03:49:29 EST 2022


Hello all

I'm hoping to end a week-long struggle by reaching out here.

We've been evaluating and testing building flask apps to give our vast
python command line tool arsenal a face lift.

I've got the basics working with coreUI for templates and flask doing the
core functionality. Or well, so it should.

I've been following tutorials and the documentation, and as far as I can
tell, we're doing everything correctly - yet it doesn't work anymore, as
soon as I make use of @login_required.

This is our routes.py:

from app.home import blueprint
from app.base.forms import LoginForm, CreateAccountForm

from flask import Flask, current_app, render_template, redirect, url_for,
request, jsonify, session
from flask_login import LoginManager, login_required, current_user,
login_user, logout_user

from app import login_manager
from app.base.models import User

app = Flask(__name__)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'home_blueprint.login'


@login_manager.user_loader
def load_user(user_id):
  print(f"User loader {user_id}")
  return User.get(user_id)

@blueprint.route('/index')
def index():
  print("Index")
  return render_template('index.html')

@blueprint.route('/contents')
@login_required
def contents():
  print("Contents")
  return ('hello', 200)


@blueprint.route('/login', methods=['GET', 'POST'])
def login():

  print(f"HEADER {request.headers}")

  login_form = LoginForm(request.form)
  if 'login' in request.form:

    # read form data
    username = request.form['username']
    password = request.form['password']


  if not current_user.is_authenticated:
    return render_template( 'accounts/login.html', form=login_form)
  return redirect(url_for('home_blueprint.index'))

If I remove @login_required from the /contents route, everything works
fine. As soon as I add it there (or anywhere else for that matter) we get
nothing but 401 Unauthorized.

This is what we use:

$ pip3 list | grep -i flask
Flask                  1.1.1
Flask-Bootstrap        3.3.7.1
Flask-Ext              0.1
flask-ldap-login       0.3.0
flask-ldap3-login      0.9.16
Flask-Login            0.5.0
Flask-Migrate          2.5.3
flask-nav              0.6
Flask-Session          0.3.2
Flask-SimpleLDAP       1.4.0
Flask-SQLAlchemy       2.4.4
Flask-WTF              0.14.3

Any hint would be greatly appreciated. The head hurts, the wall's already
got a big hole in it.


Stefan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/flask/attachments/20220224/4a0a6903/attachment.html>


More information about the Flask mailing list