有没有办法删除这段代码中的 UndefinedError?

is there a way to remove UndefinedError in this code?

我正在尝试显示从 Twitter 到我的网页的最热门话题的结果,但是当我 运行 应用程序时 return jinja2.exceptions.UndefinedError: 'trends' 未定义.我怀疑我没有按预期使用 try/except。

@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')

我也认为我的模板代码有问题。

<div class="column">
        <form  method="GET" action="{{url_for('index')}}">
            <div class="form-group">
                <p>See whats tending in your area.</p>
                <label for="">Enter location name</label>
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">
            </div>
        </form>
    </div>

    <div class="column">
        <h4>Top Trending</h4>
        <ul class="list-group">
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
          </ul>
    </div>

如果 tweepy.error.TweepError 被引发你 return render_template('index.html') 这使得 trends 在呈现此行 {% for trend in trends[0]["trends"]%} 时未定义。

你应该改变

return render_template('index.html')

return render_template('index.html', trends=None)

然后检查模板中是否传递了trends

<div class="column">
    <h4>Top Trending</h4>
    <ul class="list-group">
        {% if trends is not None %}
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
        {% endif %}
    </ul>
</div>

最好重新组织这样的事情,如果没有输入位置就不要查询,如果没有设置就不要尝试访问 trends

@app.route("/")
def index():
    location = request.args.get("location")
    trends = None
    if location:  # Only query if there is a location
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        # the above will throw an error if the place is invalid, that's fine
    return render_template("index.html", trends=trends, location=location)

<div class="column">
    <form method="GET">
        <div class="form-group">
            <p>See whats trending in your area.</p>
            <label for="">Enter location name</label>
            <input type="text" name="location" value="{{ location|default("") }}" class="form-control" id="exampleInput" placeholder="example london " required>
            <input type="submit" value="Search" class="btn btn-primary">
        </div>
    </form>
</div>


<div class="column">
    {% if trends %}
    <h4>Top Trending</h4>
    <ul class="list-group">
        {% for trend in trends[0]["trends"]%}
            <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
        {% endfor %}
      </ul>
    {% endif %}
</div>