繁体   English   中英

如何使用 Flask python 中的变量值访问 class 属性?

[英]How to access class attribute using variable value in Flask python?

我有一个表格 class

class StudentForm(FlaskForm):
      bool_1= BooleanField('Set bool_1')
      bool_2= BooleanField('Set bool_2')

现在看来,我想获得像这样的字段的值

@app.route('/student', methods=['POST'])
def student():
    fields = ['bool_1', 'bool_2']
    form = StudentForm()
    if request.method == 'POST':
       for field in fields:
         if form.field.data is True:
           print('OK')
    return render_template('abc.html', form=form)

但它显示'StudentForm' object has no attribute 'field' ,我知道该field是一个string 有什么办法可以做到这一点。

看看这个答案: https://stackoverflow.com/a/16664376/5516057 也许通读这样的内容: https://pythonise.com/series/learning-flask/flask-working-with-forms 在处理发布请求时实例化一个新的StudentForm()对我来说似乎很奇怪。 您想查看我猜测的请求产生的数据吗? 我认为您想做的看起来更像这样:

from flask import request

@app.route('/student', methods=['POST'])
def student():
    fields = ['bool_1', 'bool_2']
    form = request.form # request is a flask thing that handles the data from the request

    for field in fields:
       if form.get(field) is True: # use get, if the strings defined in fields are not in the form in the request this returns None like a normal dict I think
           print('OK')
    return render_template('abc.html', form=form)

这是一个简单的解决方案:

@app.route('/student', methods=['POST'])
def student():
    form = StudentForm()
    for k, v in form.data.items():
        if v:
            print('OK')
    return render_template('abc.html', form=form)

并且没有必要检查request.method因为你有限制methods POSTroute装饰器中发布。

暂无
暂无

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

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