无法将从 MongoDB 检索到的 json 值返回到 python flask 中的 HTML

我能够从 MongoDB 单独检索所需的值,也能够打印相同的值,但无法将所有这些值返回到 HTML 页面。当我尝试返回这些值时,尽管我在 jinja 中使用了 for 循环,但我只能看到第一个值。

我的代码如下:


@app.route('/webhookdisplay', methods=['POST', 'GET'])

def webhooksdis():

    collection10 = db['webhooks']

    a = collection10.find({"name": "abc"}, {'_id': 0, 'recorded_at':0, 'expiry_time': 0, 'version': 0, 'created_at': 0, 'account_id': 0, 'device_id': 0})

    for i in collection10.find({}):

        d = i.get('data', {}).get('geometry', {}).get('coordinates')

        print(d)

        name = i.get('data', {}).get('geofence_metadata', {}).get('name')

        print(name)

    return render_template("webhooks.html",  name = name, a = a, d =d)

在上面的代码名称中也有 None 值,所以当我尝试单独返回它时显示 TypeError: 'NoneType' object is not iterable。假设如果我返回那些没有 None 值的值,它会返回但只显示第一个值。


HTML代码


{% for i in d %}

{{ i }} 

{% endfor %}<br />

这个 jinja 适用于所有值,但我需要在烧瓶中检索的单个值:


<table>   

<th>           

{% for item in a %} 

</th>

<tr>

<td><th>   {% for key, value in item.items() %} </th>  </td>

<td><span>{{ key }} : {{ value }}</span> </td>

<br />

<td>{% endfor %}</td>

<td>{% endfor %}</td>

</tr>   

</table>



**预期输出** 应返回所有值,包括 None 值,我正在 flask 中检索这些值,以便我可以在 HTML 页面中呈现


慕沐林林
浏览 130回答 3
3回答

MYYA

您可以使用jinja进行模板渲染。使用下面的伪代码,您可以填充 JSON 数据:{% for key, value in a %}           <span>{{key}} : {{value}}</span> {% endfor %}

紫衣仙女

什么是输出:print(request.data)print(request.form)print(request.json)print(request.get_json())&nbsp;&nbsp;?更新:a是一个列表。所以尝试:{% for item in a %}&nbsp;&nbsp; &nbsp; {% for key, value in item.items() %}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <span>{{ key }} : {{ value }}</span><br />&nbsp; &nbsp; {% endfor %}{% endfor %}

拉风的咖菲猫

if&nbsp;a:&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;filtered_data=[{"name":device["name"]}&nbsp;for&nbsp;device&nbsp;in&nbsp;a]&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;print(filtered_data)&nbsp; else:&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;print("Document&nbsp;does&nbsp;not&nbsp;exist&nbsp;!")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python