【问题标题】:Displaying data from dictionary using flask, pythonanywhere使用烧瓶,pythonanywhere 显示字典中的数据
【发布时间】:2016-12-08 15:46:46
【问题描述】:

我正在尝试使用 pythonanywhere 烧瓶应用程序显示一些简单的 3 天天气预报数据。到目前为止,这是我的代码:

from flask import Flask, render_template
import requests
from collections import defaultdict


app = Flask(__name__)

r = requests.get("http://api.wunderground.com/api/mykey/forecast/q/SouthAFrica/Stellenbosch.json")
data = r.json()
weather_data = defaultdict(list)

counter = 0
for day in data['forecast']['simpleforecast']['forecastday']:
    date= day['date']['weekday'] + ":"
    cond=  "Conditions: ", day['conditions']
    temp= "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C"


    counter = counter + 1

    weather_data[counter].append(date)
    weather_data[counter].append(cond)
    weather_data[counter].append(temp)

return weather_data

@app.route('/')
def home():
    return render_template('home.html', weather_data=weather_data)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

这里是简单的“home.html”:

<table>
{% for key,value in weather_data.items() %}
    <tr>
        <td>{{value[1]}}</td>
        <td>{{value[2]}}</td>
        <td>{{value[3]}}</td>
        <td>{{value[4]}}</td>
    </tr>
{% endfor %}
</table>

我似乎无法让它工作。我怀疑这与数据的格式有关?它应该是一个单独的导入文件吗?

【问题讨论】:

  • 你没有说问题出在哪里,但我怀疑这与在茫茫荒野中的悬空返回有关。

标签: python flask jinja2 pythonanywhere


【解决方案1】:

将 python 逻辑放在视图函数中,如下所示:

@app.route('/')
def home():
    r = requests.get("http://api.wunderground.com/api/key/forecast/q/SouthAfrica/Stellenbosch.json")
    data = r.json()
    weather_data = defaultdict(list)

    counter = 0
    for day in data['forecast']['simpleforecast']['forecastday']:
        date = day['date']['weekday'] + ":"
        cond = "Conditions: ", day['conditions']
        temp = "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C"

        counter += 1

        weather_data[counter].append(date)
        weather_data[counter].append(cond)
        weather_data[counter].append(temp)

    return render_template('home.html', weather_data=weather_data)

通过查看 API 数据,我认为您的 {{ value[1] }} 仍然是一个元组,因此您可能需要在模板中使用类似 {{ value[1][0] }}, {{ value[1][1] }} 的内容来呈现此数据。

在你的python中添加打印语句来调试如何解析数据结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2021-12-26
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2021-06-20
    相关资源
    最近更新 更多