Есть ли способ удалить UndefinedError в этом коде? - PullRequest
0 голосов
/ 19 февраля 2020

Я пытаюсь отобразить результаты самых популярных тем из твиттера на моей веб-странице, но когда я запускаю приложение, оно возвращает jinja2.exceptions.UndefinedError: «тренды» не определены. Я подозреваю, что я не использую try /, за исключением того, как он должен.

@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>

Ответы [ 2 ]

0 голосов
/ 19 февраля 2020

Лучше реорганизовать что-то вроде этого, чтобы не запрашивать вещи, если не указано местоположение, и не пытаться получить доступ к 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>
0 голосов
/ 19 февраля 2020

Если вы подняли 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>
...