FLASK中不存在的参数的例外 [英] exception for non existing parameter in FLASK

查看:540
本文介绍了FLASK中不存在的参数的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发送参数的表单。
在我的表单中,我有一个复选框。
如果我的复选框没有被选中,那么我将不会得到任何参数。

如果在我的模块中有:

  var = request.form ['mycheckbox'] 



然后在调试模式下,我收到错误消息:




错误的请求浏览器(或代理)发送了一个请求,表示服务器
无法理解。


没有告诉我有什么错误。

我通过使用以下方法防止了异常:

 尝试:
var = request.form ['checkbox']
除了:
var =无

但是我不能改变Flask如何处理这种情况的行为吗?

解决方案

这里的原因隐藏在烧瓶文档中: http://flask.pocoo.org/docs/api/#flask.Flask.trap_http_exception



我是不知道为什么在调试模式下这种行为没有改变,但是为了让Flask能够捕获来自werkzeug的BadRequestKeyError异常,你需要在你的应用程序对象上运行这样的东西:

  app.config ['TRAP_BAD_REQUEST_ERRORS'] = True 


I have a form that sends parameters. In my form I have a checkbox. If my checkbox is not checked then I will not get any parameters.

If in my module I have :

var = request.form['mycheckbox']

and if my checkbox is not checked (the parameter is not passed)

Then in debug mode I get the error message :

Bad Request The browser (or proxy) sent a request that this server could not understand.

Nothing tells me about what the error is.

I prevented the exception by using :

    try:
        var=request.form['checkbox']
    except:
        var=None

But can I not change the behavior of how Flask handles this case ?

解决方案

The reason for this is hidden in the flask documentation here: http://flask.pocoo.org/docs/api/#flask.Flask.trap_http_exception

I'm not sure why this behaviour isn't changed for debugging mode, but to get Flask to catch the BadRequestKeyError exceptions from werkzeug, you need to run something like this on your application object:

app.config['TRAP_BAD_REQUEST_ERRORS'] = True

这篇关于FLASK中不存在的参数的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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