python - 有没有办法在这段代码中删除 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>
解决方案
如果在渲染这条线时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>
推荐阅读
- c++ - CGAL - 如何使用 CGAL::Polygon_mesh_processing::connected_components 将一个 CGAL::Surface_mesh 转换为多个?
- ecmascript-6 - 我应该使用什么类型在 jsdoc 中记录 ES6 模块参数?
- java - 我需要从 Farm 类的 Employee 类中获取最大值
- vb.net - 从列表框中列出的文本文件中删除行
- android - 即使在 Play 商店中关闭自动更新,如何让我的应用更新?
- php - 使用准备好的语句进行全文搜索返回空数组
- javascript - ajax 无法将请求发送到另一个 php 页面
- python - 如何裁剪轮廓?
- python - GSSException:尝试使用 kerberos 票证进行身份验证时未找到以下凭据:1.2.840.113554.1.2.2
- jquery - Axaj 呼叫而不重新加载页面?