首页 > 解决方案 > 有没有办法在这段代码中删除 UndefinedError ?

问题描述

我正在尝试将最热门话题的结果从 twitter 显示到我的网页,但是当我运行应用程序时,它返回 jinja2.exceptions.UndefinedError: 'trends' is undefined。我怀疑我没有使用 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>

标签: pythonflasktweepy

解决方案


如果在渲染这条线时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>

推荐阅读