如何重写这个Flask视图函数来遵循post / redirect / get模式? [英] How to rewrite this Flask view function to follow the post/redirect/get pattern?

查看:333
本文介绍了如何重写这个Flask视图函数来遵循post / redirect / get模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小日志浏览器。它根据用户的输入检索并显示以前记录的记录列表。它不会更新任何东西。



代码非常简单,工作正常。这是一个简化的版本:

  @ app.route('/ log',methods = ['GET','POST' ])
def log():
form = LogForm()
if form.validate_on_submit():
args = parse(form)
return render_template('log .html',form = form,log = getlog(* args))
return render_template('log.html',form = form)

然而,它并不遵循post / redirect / get模式,我想解决这个问题。

我应该在哪里存储post和get之间的发布数据(即 args )?什么是标准或推荐的方法?我应该设置一个cookie吗?我应该使用flask.session对象,在那里创建一个缓存?你能指点我正确的方向吗?大部分时间我正在写后端...


$ b $ p

更新:


$ b

  @ app.route('/ log',methods = [ ')
def log_post():
form = LogForm()
if form.validate_on_submit():
session ['logformdata'] = form.data
return redirect(url_for('log'))
#或者在这里刷新错误或者在模板中显示
return render_template('log.html',form = form)

@ app.route('/ log',methods = ['GET'])
def log():
try:
formdata = session.pop('logformdata')
除了KeyError:
return render_template('log.html',form = LogForm())

args = parse(formdata)
log = getlog(args)
return render_template('log.html',form = LogForm(data = formdata),log = log)


解决方案

所以,最终 post / redirect / get pattern 可以防止多次提交表单数据。由于你的 POST 这里实际上并没有做任何数据库更改,所以你使用的方法似乎很好。通常情况下, POST 改变底层数据结构(例如UPDATE / INSERT / DELETE),然后在重定向时查询更新数据(SELECT)不需要在重定向和获取之间存储任何东西。

有了所有的说法,我的方法就是使用Flask session 对象,这是Flask为您管理的一个cookie。你可以这样做:

  @ app.route('/ log',methods = ['GET','POST '))
def log():
form = LogForm()
if form.validate_on_submit():
args = parse(form)
session ['log '] = getlog(* args)
return redirect(url_for('log'))
saved = session.pop('log',None)
return render_template('log.html' ,form = form,log = saved)

另外,要使用session,你必须有一个 secret_key 设置为应用程序配置的一部分。



Flask Session API

UPDATE 1/9/16



根据ThiefMaster的评论,在这里重新安排了逻辑顺序,允许使用WTForms验证方法来处理无效的表单提交,因此无效的表单提交不会丢失。

I have a small log browser. It retrieves and displays a list of previously logged records depending on user's input. It does not update anything.

The code is very simple and is working fine. This is a simplified version:

@app.route('/log', methods=['GET', 'POST'])
def log():
    form = LogForm()
    if form.validate_on_submit():
        args = parse(form)
        return render_template('log.html', form=form, log=getlog(*args))
    return render_template('log.html', form=form)

However it does not follow the post/redirect/get pattern and I want to fix this.

Where should I store the posted data (i.e. the args) between post and get? What is the standard or recommended approach? Should I set a cookie? Should I use flask.session object, create a cache there? Could you please point me in the right direction? Most of the time I'm writing backends...


UPDATE:

I'm posting the resulting code.

@app.route('/log', methods=['POST'])
def log_post():
    form = LogForm()
    if form.validate_on_submit():
        session['logformdata'] = form.data
        return redirect(url_for('log'))
    # either flash errors here or display them in the template
    return render_template('log.html', form=form)

@app.route('/log', methods=['GET'])
def log():
    try:
        formdata = session.pop('logformdata')
    except KeyError:
        return render_template('log.html', form=LogForm())

    args = parse(formdata)
    log = getlog(args)
    return render_template('log.html', form=LogForm(data=formdata), log=log)

解决方案

So, ultimately the post/redirect/get pattern protects against submitting form data more than once. Since your POST here is not actually making any database changes the approach you're using seems fine. Typically in the pattern the POST makes a change to underlying data structure (e.g. UPDATE/INSERT/DELETE), then on the redirect you query the updated data (SELECT) so typically you don't need to "store" anything in between the redirect and get.

With all the being said my approach for this would be to use the Flask session object, which is a cookie that Flask manages for you. You could do something like this:

@app.route('/log', methods=['GET', 'POST'])
def log():
    form = LogForm()
    if form.validate_on_submit():
        args = parse(form)
        session['log'] = getlog(*args)
        return redirect(url_for('log'))
    saved = session.pop('log', None)
    return render_template('log.html', form=form, log=saved)

Also, to use session, you must have a secret_key set as part of you application configuration.

Flask Session API

UPDATE 1/9/16

Per ThiefMaster's comment, re-arranged the order of logic here to allow use of WTForms validation methods for invalid form submissions so invalid form submissions are not lost.

这篇关于如何重写这个Flask视图函数来遵循post / redirect / get模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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