我正在尝试使用 pythonanywhere Flask 应用程序显示一些简单的 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 逻辑放入 View 函数中,如下所示:
@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中以调试如何解析数据结构。
关于python - 使用flask、pythonanywhere显示字典中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043390/