jinja2.exceptions.UndefinedError:'响应'未定义

当我尝试遍历json输出的元素时,出现上述错误。 这是我的 app.py 文件

from flask import flask,render_template,request
from elasticsearch import Elasticsearch

app = flask(__name__)
es = Elasticsearch()
@app.route('/',methods=["GET","POST"])
def index():
    q = request.form.get("q")
    if q is not None:
        resp = es.search(index='aman',body={"query": {"match":{"NAME": q}}})
        return render_template('index.html',q=q,response=resp)
    return render_template('index.html')

if __name__ =="__main__":
    app.run(debug=True)

这是我的 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/" method="post" autocomplete="off">
        <label for="q"> search here : </label><input type="text" name="q" id="q" value="{{q}}">
        <input type="submit" value="search">

    <ol>
        {% for resp in response.hits.hits %}
        <li><a href="{{resp._source.url}}"> {{resp._source.NAME}}</a></li>
        {% endfor %}
    </ol>  

</form>
</body>
</html>

令人惊讶的是,当我用 {{response}} 替换有序列表标签之间的内容时,程序运行无错误,并且“ response”变量中的数据打印在网页上。 请指导我。

oye07 回答:jinja2.exceptions.UndefinedError:'响应'未定义

我知道了。发布解决方案,因为它对于遇到类似问题的人可能会很方便。
 在 app.py 文件中,将 response = resp 替换为 response = resp [“ hits”] [“ hits”] 并在 index.html 文件中,将 response.hits.hits 替换为 response

本文链接:https://www.f2er.com/3115235.html

大家都在问