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?
Advertisement
Answer
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/