api - 在 Django 中的 API URL 中传递参数
问题描述
我正在玩 API,这是我的第一个 API 视图,请帮助我理解我错在哪里。
我使用这个 API api.openweathermap.org/data/2.5/weather?q={city name},{country code} 我写了这个视图:
def forecast(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q= {}&appid=My_Key'
cities = {'city': 'London', 'cod' : 826}
city_weather = requests.get(url.format(cities)).json()
weather = {
'temperature': city_weather['main']['temp'],# one parameter, just to check whethe it works
}
context = {'weather' : weather }
return render(request, 'weather/forecast.html')
这是非常基本的视图,就像我的第一个 print("Hello, World!") ,但 id 根本不起作用))如果您建议我一些关于此的文章,我将不胜感激。在这里没有找到答案http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content
解决方案
您需要将保存的数据传递到视图中
context = {'weather' : weather }
return render(request, 'weather/forecast.html', context=context)
然后,您可以访问context
hmtl 脚本内的变量中的数据
<div>
{{ weather }}
</div>
推荐阅读
- python - 如何在 Google Drive Api v3 中进行部分下载?
- rest - 在 teamcity 上构建/测试监控工具
- c# - 如何从编辑器脚本中的 MonoBehaviour 脚本访问和更新列表?
- tensorflow - ValueError:未知初始化程序:GlorotUniform
- javascript - 使用链接 React-Bootstrap 控制轮播
- javascript - 如何仅针对Angular7中的字母数字和特殊字符触发keydown事件?
- javascript - 用于检测视频点击的跨浏览器解决方案?
- python - Selenium 仅在 Headless 中运行 ChromeDriver
- c# - C#浮点到双精度转换
- dns - 如果我将书签的 IP 地址而不是主机名存储在书签中,我是否能够更快地访问书签?