当前位置: 首页 > 面试题库 >

通过Flask-Login进行身份验证后,存储帖子数据以供使用

彭雨华
2023-03-14
问题内容

每个文章页面都有一个表单,供登录用户添加评论。我希望用户即使尚未登录也能够发表评论。应将它们重定向到登录页面,然后添加注释。但是,当Flask-Loginlogin_required重定向重定向回页面时,它不是POST请求,并且不会保留表单数据。登录并重定向后,是否可以保留POST数据?

@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'))

问题答案:

由于必须登录后才能发布用户,因此如果用户未登录,则仅显示“单击此处登录”链接而不是表单是更有意义的。

如果确实要执行此操作,则可以在重定向到登录路径时在会话中存储任何表单数据,然后在返回注释路径时检查此存储的数据。同时存储请求的路径,以便仅当你返回同一页面时才可以恢复数据。要存储数据,你需要创建自己的login_required装饰器。

request.form.to_dict(flat=False)会将MultiDict数据转储到列表的字典中。这可以存储在中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)


 类似资料:
  • 我是Spring安全的新手,我想用数据库验证用户。我已经用jdbc创建了一个登录页面和一个身份验证提供程序,它检查用户是否存在于数据库中。但是我的代码没有这样做的问题是,它允许所有用户登录!我的代码怎么了?谢谢你的帮助。 这是我的安全会议。xml:

  • 我已经创建了一个android应用程序,并使用firebase作为电子邮件注册和认证的手段。注册后,用户可以在数据库中存储库存项目。所以我的问题是,如何设置firebase身份验证规则,以便特定用户只能访问他们输入的数据。现在,每个人都可以读/写数据库。我不担心写的部分,因为电子邮件认证。提前感谢! 我的数据库是这样设置的:数据库

  • 问题: 我们有一个spring的基于MVC的RESTful API,它包含敏感信息。API应该是安全的,但是不希望在每个请求中发送用户的凭据(User/Pass组合)。根据REST指南(和内部业务需求),服务器必须保持无状态。API将由另一台服务器以混搭方式使用。 要求: > 客户端请求使用凭据(不受保护的URL);服务器返回一个安全令牌,该令牌包含足够的信息,供服务器验证未来的请求并保持无状态。

  • 我是身份验证方面的新手。我有一个应用程序,登录后,向服务器发送凭据,服务器生成令牌并将其发送回客户端(移动设备)。 这是我的问题:在可用后,我应该在哪里存储即将到来的请求的信息?例如,如果我想发送请求,我有两种方法: < li >在请求的< code>body上存储所需的信息 < li >使用< code>Base64中的< code>JSON格式对信息进行编码后,将其存储在< code>JWT的

  • 在我配置了下面的配置之后,它不会连接到Active Directory。我无法使用Active Directory的帐户登录。会有什么问题? 我有一个Ubuntu服务器18.04,带有ApacheGuacamoleV1。0.0. 安装。我想使用LDAP身份验证来验证用户。我已经下载了鳄梨酱-auth-ldap-1.0.0。jar和jldap-4.3。jar扩展。 10.10.10.21,10.10

  • 我是新的Firebase.我已经建立了一个Firebase实时数据库,如果读写规则设置为true,可以读写它。 我的身份验证有问题。我已经为谷歌和电子邮件加密码设置了身份验证。 我的目标是允许任何用户读取数据,但只有一个用户(我自己)可以在使用单个电子邮件地址和密码登录后写入数据。 如果我用谷歌登录,我可以成功地读写数据库(规则设置为: auth!=null)。 如果使用电子邮件地址和密码登录,我