循环遍历数据库结果在python / flask中

时间:2016-11-28 11:42:32

标签: python python-3.x flask

我从我的数据库中获得以下结果集

    {
  "workbases": [
    {
      "workbase": "WB 1"
    }, 
    {
      "workbase": "WB 2"
    }, 
    {
      "workbase": "WB 3"
    }, 
    {
      "workbase": "WB 4"
    }, 
    {
      "workbase": "WB 5"
    }, 
    {
      "workbase": "WB 6"
    }, 
    {
      "workbase": "WB 7"
    }, 
    {
      "workbase": "WB 8"
    }, 
    {
      "workbase": "WB 9"
    }, 
    {
      "workbase": "WB 10"
    }, 
    {
      "workbase": "WB 11"
    }, 
    {
      "workbase": "WB 12"
    }, 
    {
      "workbase": "WB 13"
    }, 
    {
      "workbase": "WB 14"
    }, 
    {
      "workbase": "WB 15"
    }, 
    {
      "workbase": "WB 16"
    }
  ]
}

这些结果来自此代码,

staff = tables.staff_list

sel = select([staff.c.workbase]).distinct(staff.c.workbase).select_from(staff).where(staff.c.workbase != "")

workbases = FlaskApp.db_connect().execute(sel).fetchall()
workbases = [utils.rowdict(a) for a in workbases]

workbases = jsonify(workbases=workbases)

return render_template('leave_request.html', hours_left=100, workbases=workbases)

如何查看模板中的工作区数据,我尝试过,

{% for w in workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

以及

{% for w in workbases.workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

但是他们中的任何一个都在我的选择输入中呈现任何选项(代码嵌套在select标签中

2 个答案:

答案 0 :(得分:0)

你试过吗

{% for w in workbases['workbases'] %}
    <option value="">{{ w['workbase'] }}</option>
{% endfor %}

答案 1 :(得分:0)

如果从python文件中删除行workbases = jsonify(workbases=workbases)。正如cricket007所述,jsonify是一个flask.Response()对象,用于将Flask中的JSON数据发送到类似XHR调用或API调用的对象。它是一个HTTP响应,将包含内容标题等。

删除后,您描述的第二个Jinja2方法应该有效。

{% for w in workbases.workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

这将产生与以下相同的结果:

{% for w in workbases['workbases'] %}
    <option value="">{{ w['workbase'] }}</option>
{% endfor %}

因为Jinja2不是Python。有关更多详细信息,请参阅文档:

http://jinja.pocoo.org/docs/dev/templates/#variables