【问题标题】:Unable to return json values retrieved from MongoDB to HTML page in python flask无法将从 MongoDB 检索到的 json 值返回到 python 烧瓶中的 HTML 页面
【发布时间】:2020-11-22 05:30:15
【问题描述】:

我能够单独从 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 />

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

<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 值,我在烧瓶中检索这些值,以便我可以在 HTML 页面中呈现

【问题讨论】:

    标签: python json python-3.x flask pymongo


    【解决方案1】:

    输出是什么:

    print(request.data)
    print(request.form)
    print(request.json)
    print(request.get_json())  
    

    ?

    更新:

    a 是一个列表。所以试试:

    {% for item in a %} 
        {% for key, value in item.items() %}        
            <span>{{ key }} : {{ value }}</span><br />
        {% endfor %}
    {% endfor %}
    

    【讨论】:

    • request.data: b'[\r\n {\r\n "Language" : "python"\r\n }\r\n]' request.form: ImmutableMultiDict([] ) request.json: [{'Language': 'python'}] request.get_json(): [{'Language': 'python'}] 这是我得到的输出@GAEfan
    • 我收到 TypeError: 'NoneType' object is not iterable。在邮递员响应中,我能够看到包括 JSON 值在内的整个 HTMlL 代码,但在服务器 HTML 页面中我收到错误
    【解决方案2】:

    您可以使用jinja 进行模板渲染。

    使用下面的伪代码可以填充 JSON 数据:

    {% for key, value in a %}        
      <span>{{key}} : {{value}}</span>
    {% endfor %}
    

    【讨论】:

    • 我收到 TypeError: 'NoneType' object is not iterable
    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多