我正在尝试使用pythonanywhere flask app显示一些简单的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>
我似乎无法让这个工作。我怀疑它与数据格式有关?它应该是一个单独的文件导入?
答案 0 :(得分:1)
将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中以调试如何解析数据结构。