exception for non existing parameter in FLASK

元气小坏坏 提交于 2019-11-29 18:17:39

问题


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 ?


回答1:


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



回答2:


var = request.form.get('checkbox')

This will return None if the parameter is not defined.




回答3:


I had similar issue during validation of single boolean field.

I solved it by using remember = form.rememberme.data instead of request.form['remember_me']



来源:https://stackoverflow.com/questions/8896473/exception-for-non-existing-parameter-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!