gpt4 book ai didi

python - 存储发布数据以供在使用 Flask-Login 进行身份验证后使用

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:23 25 4
gpt4 key购买 nike

每个文章页面都有一个表单供登录用户添加评论。我希望用户即使尚未登录也能发表评论。他们应该被重定向到登录页面,然后应该添加评论。但是Flask-Login的login_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'))

最佳答案

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


如果你真的想这样做,你可以在重定向到登录路由时在 session 中存储任何表单数据,然后在你返回评论路由时检查这些存储的数据。同时存储请求的路径,以便只有返回同一页面时才会恢复数据。要存储数据,您需要创建自己的 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)

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

关于python - 存储发布数据以供在使用 Flask-Login 进行身份验证后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com