python - 使用flask、pythonanywhere显示字典中的数据

标签 python flask jinja2 pythonanywhere

我正在尝试使用 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/

相关文章:

python - 从 Python 调用 C 函数

python - 在 Python 中实现传输层安全 - 简单的邮件客户端

python - 在python中接收并循环遍历json数据

python - 是否可以限制 Flask 请求触发的 CPU/内存使用?

python - Jinja2 字典列表到 HTML 表中?

python - sample() 和 rsample() 有什么区别?

python - 多步预测 LSTM 模型

python - 仅当输入少于 3 个字符时,WTForms 返回 None

jinja2 - 如何在 PyGears 中集成 jinja 模块

python - 谷歌应用程序引擎的顶级用户身份验证方法