0

如何使用 mako 或 jinja 模板显示从 json 到 html 的数据。

这是我的 json 文件

{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [ {
      "id": 300,
      "main": "Drizzle",
      "description": "light intensity drizzle",
      "icon": "09d"
    }],
  "base": "stations",
  "main": {"temp": 280.32,
    "pressure": 1012,
    "humidity": 81,
    "temp_min": 279.15,
    "temp_max": 281.15 },
  "visibility": 10000,
  "wind": {
    "speed": 4.1,
    "deg": 80
  },
  "clouds": {
    "all": 90
  },
  "dt": 1485789600,
  "sys": {
    "type": 1,
    "id": 5091,
    "message": 0.0103,
    "country": "GB",
    "sunrise": 1485762037,
    "sunset": 1485794875
  },
  "id": 2643743,
  "name": "London",
  "cod": 200
}

这是我用于下载 JSON API 的 python 代码:

import json

import requests

res = requests.get('https://samples.openweathermap.org/data/2.5/weather? 
q=London,uk&appid=b6907d289e10d714a6e88b30761fae22')

print (res.json())

res_text= res.text
print(type(res_text))

data=json.loads(res_text)
print(type(data))

data_serialized= json.dump(data, open('data.json', "w"),indent=2)

输出应该是:

London, GB  light rain
6°С temperature from 5 to 7.2 °С, wind 8.2 m/s. clouds 100 %, 974 hPa
4

1 回答 1

1

将数据传递给模板并通过 jinja 模板进行访问,例如:在视图结束时:

return render_template(<template_file>, data=<json-data>)

在模板文件中:

{{data.name}}, {{data.sys.country}} {{data.weather.description}} 

对其他人也是如此。

于 2020-01-24T06:40:35.987 回答