Flask 302 error code when using flask.redirect

Question:

I have this code https://github.com/italomaia/flask-empty/blob/master/src/0.8/main.py and I wrote at the end of the file:

def configure_before_request(app):
    @app.before_request
    def before_request():
        hash = pbkdf2_sha256.encrypt(app.config['PASSWORD'], rounds=8000, salt_size=10)
        if session.get('logged_in') != hash:
            return redirect(url_for('login'))
def configure_views(app):
    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            hash = pbkdf2_sha256.encrypt(app.config['PASSWORD'], rounds=8000, salt_size=10)
            if request.form['login'] == app.config['USERNAME'] and pbkdf2_sha256.verify(request.form['password'], hash):
                session['logged_in'] = hash
                return redirect(url_for('index'))
            else:
                flash(u'Неверный логин или пароль')
        return render_template('login.html')

    @app.route('/', methods=['GET', 'POST'])
    def index():
        return 'index_page НАХ.'

If I run this code, I get 302 server error (ERR_TOO_MANY_REDIRECTS), but if I change this line return redirect(url_for('login')) by return 'Hello!' it works without errors! What am I doing wrong?

Asked By: Nolik

||

Answers:

Well I am not a specialist on flask. But obviously you are using a signal before the request gets mapped to a handler to check for credentials and then redirect to a handler. But the redirect in turn will trigger another request to your app and invoke the same function again, sending you into an infinite redirect loop.
(Error 302 is a specific http error for this situation)

My advice: Check for credentials on per handler function basis or make at least an exception to your before_request function that it doesn’t get invoked when a request to “login/” occurs.

It might also be possible to directly invoke the function that handles login/

Answered By: simlan

Replace

if session.get('logged_in') != hash:

by

if session.get('logged_in') != hash and request.endpoint != 'login':

This answer was posted as an edit to the question Why i get 302 error on flask.redirect by the OP Nolik under CC BY-SA 3.0.

Answered By: vvvvv
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.