简体   繁体   English

如何使用Python Flask启用复选框,而不会引起400错误的请求错误?

[英]How do I get checkbox “on” using Python Flask without causing a 400 bad request error?

I've got a form which is submitting a post request to Flask. 我有一个表格正在向Flask提交发帖请求。 It all works perfectly except when a checkbox is not ticked which causes a 400 error unless I have a try: except: catch for each option. 除非我没有勾选复选框,否则会导致400错误,除非我尝试使用try:except:捕获每个选项,否则所有方法都可以正常工作。

The challenge is that I have a lot of checkboxes and it seems like there would be a better way than just having a dozen try: except: checks. 面临的挑战是我有很多复选框,而且似乎有比只尝试一打更好的方法:例外:检查。

Is there a more Pythonic way of doing this please? 请问有没有更Python化的方式来做到这一点?

Currently the HTML looks like this: 目前,HTML如下所示:

<div class="control">
  <label class="checkbox">
    <input name="option_1" type="checkbox">
     Option 1
    </label>
</div>

My Python code looks like: 我的Python代码如下所示:

try:
    print(request.form['option_1'])

except:
    print("option_1 not selected")

如果某个键可能不存在,请使用.get(...)而不是直接访问它,例如:

print(request.form.get('option_1'))

Thanks to Janos for the explanation, whoop only prints if the box is ticked with no error if it's not there. 多亏了Janos的解释,如果方格打勾,则只有当方格打勾时才显示错误提示。

if request.form.get('option_1'):
        print('whoop')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM