Store post data for use after authenticating with Flask-Login

倾然丶 夕夏残阳落幕 提交于 2019-12-01 11:04:49

Since users have to be logged in to post, it would make more sense to just show a "click here to log in" link instead of the form if the user is not logged in.


If you really want to do this, you can store any form data in the session when redirecting to the login route, then check for this stored data once you're back in the comment route. Store the requested path as well, so that the data will only be restored if you go back to the same page. To store the data you'll need to create your own login_required decorator.

request.form.to_dict(flat=False) will dump the MultiDict data to a dict of lists. This can be stored in the session.

from functools import wraps
from flask import current_app, request, session, redirect, render_template
from flask_login import current_user
from werkzeug.datastructures import MultiDict

def login_required_save_post(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_app.login_manager._login_disabled or current_user.is_authenticated:
            # auth disabled or already logged in
            return f(*args, **kwargs)

        # store data before handling login
        session['form_data'] = request.form.to_dict(flat=False)
        session['form_path'] = request.path
        return current_app.login_manager.unauthorized()

    return decorated

@app.route('/article/<int:id>', methods=['GET', 'POST'])
@login_required_save_post
def article_detail(id):
    article = Article.query.get_or_404(id)

    if session.pop('form_path', None) == request.path:
        # create form with stored data
        form = CommentForm(MultiDict(session.pop('form_data')))
    else:
        # create form normally
        form = CommentForm()

    # can't validate_on_submit, since this might be on a redirect
    # so just validate no matter what
    if form.validate():
        # add comment to article
        return redirect(request.path)

    return render_template('article_detail.html', article=article)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!