在使用Flask-Login进行身份验证之后,存储发布数据以供使用 [英] Store post data for use after authenticating with Flask-Login

查看:218
本文介绍了在使用Flask-Login进行身份验证之后,存储发布数据以供使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每篇文章页面都有登录用户添加评论的表单。我希望用户能够评论,即使他们还没有登录。他们应该被重定向到登录页面,然后添加评论。但是,当Flask-Login的 login_required 重定向回页面时,它不是POST请求,并且表单数据不会保留。有没有办法在登录和重定向后保存POST数据?

  @ articles.route('/ articles /< def article_get(article_id):
form = CommentForm(article_id = article_id)

if request。方法=='POST':
if form.validate_on_submit():
如果current_user.is_authenticated():
返回_create_comment(form,article_id)
else:
(app.config ['BASE'],article_id))
article文章['time_created'],'r_json()''article']
comments = r.json()['comments']
article ['time_created'] = datetime.strptime %a,%d%b%Y%H:%M:%S%Z')

评论评论:
comment ['time_created'] = datetime.strptime(comment ['time_created'],'%a,%d%b%Y %H:%M:%S%Z')

return render_template('articles / article_item.html',article = article,comments = comments,form = form)

$ def_create_comment(form,article_id):
headers = {'Content-type':'application / json','Accept':'text / plain'}
data = {'body':form .body.data,'article_id':article_id,'user_id':current_user.id}
r = requests.post('%s / articles / comment /'%app.config ['BASE'],data = json .dumps(data),headers = headers)
return redirect(url_for('。article_get',article_id = article_id,_anchor ='comment-set'))
pre

解决方案

由于用户必须登录后才能显示点击这里登录如果用户没有登录,那么在链接而不是表单中。






如果你真的想这样做,可以在重定向到登录路由时在会话中存储任何表单数据,然后检查这个存储的数据一旦你回到评论路线。保存请求的路径,以便只有当你回到同一页面时才能恢复数据。要存储数据,您需要创建自己的 login_required 装饰器。

  from functools导入包装
从烧瓶导入current_app,request,session,redirect,render_template $ b $ from flask_login import current_user $ b $ from werkzeug.datastructures导入MultiDict

def login_required_save_post (f):
@wraps(f)
def装饰(* args,** kwargs):
如果current_app.login_manager._login_disabled或current_user.is_authenticated:
#auth已禁用或已经登录
return f(* args,** kwargs)

#处理登录前存储数据
session ['form_data'] = request.form.to_dict(flat = False)
session ['form_path'] = request.path
返回current_app.login_manager.unauthorized()

返回装饰

@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:
#使用存储的数据创建表单
form = CommentForm(MultiDict(session.pop('form_data')))
else:
#通常创建表单
form = CommentForm ()

#无法validate_on_submit,因为这可能是一个重定向
#所以只是验证无论
如果form.validate():
#给文章添加评论
return redirect(request.path)

return render_template('article_detail.html',article = article)


Each article page has a form for logged in users to add a comment. I want users to be able to comment even if they haven't logged in yet. They should be redirected to the login page, and then the comment should be added. However, when Flask-Login's login_required redirects back to the page, it is not a POST request, and the form data is not preserved. Is there a way to preserve the POST data after logging in and redirecting?

@articles.route('/articles/<article_id>/', methods=['GET', 'POST'])
def article_get(article_id):
    form = CommentForm(article_id=article_id)

    if request.method == 'POST':
        if form.validate_on_submit():
            if current_user.is_authenticated():
                return _create_comment(form, article_id)
        else:
            return app.login_manager.unauthorized()

    r = requests.get('%s/articles/%s/' % (app.config['BASE'], article_id))
    article = r.json()['article']
    comments = r.json()['comments']
    article['time_created'] = datetime.strptime(article['time_created'], '%a, %d %b %Y %H:%M:%S %Z')

    for comment in comments:
        comment['time_created'] = datetime.strptime(comment['time_created'], '%a, %d %b %Y %H:%M:%S %Z')

    return render_template('articles/article_item.html', article=article, comments=comments, form=form)

def _create_comment(form, article_id):
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    data = {'body': form.body.data, 'article_id': article_id, 'user_id': current_user.id}
    r = requests.post('%s/articles/comment/' % app.config['BASE'], data=json.dumps(data), headers=headers)
    return redirect(url_for('.article_get', article_id=article_id, _anchor='comment-set'))

解决方案

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.

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)

这篇关于在使用Flask-Login进行身份验证之后,存储发布数据以供使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆