【发布时间】:2019-01-27 22:48:29
【问题描述】:
index 函数从 'n url 检索字符串并将所需的输出打印到终端。如何设置我的视图,以便它在我的索引 html 页面上显示数据?
这适用于需要从 URL 检索数据并将其显示在用户登录的页面上的天气应用程序。我已尝试使用上下文,但我不确定如何将它与返回的数据一起使用从 for 循环。
from django.shortcuts import render
import requests
import json
def index(request):
url = "http://weather.news24.com/ajaxpro/Weather.Code.Ajax,Weather.ashx"
headers = {'Content-Type': 'text/plain; charset=UTF-8',
'Host': 'weather.news24.com',
'Origin': 'http://weather.news24.com',
'Referer': 'http://weather.news24.com/sa/capetown',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'X-AjaxPro-Method': 'GetForecast7Day'}
payload = {"cityId": "77107"}
r = requests.post(url, headers=headers, data=json.dumps(payload))
weather_data = r.json()
for forecast in weather_data['value']['Forecasts']:
print(forecast['ShortWeekDay'] + ':', 'High: ' + forecast['HighTemp'] + 'C',
'Low: ' + forecast['LowTemp'] + 'C',
'Wind Speed: ' + forecast['WindSpeed'] + 'Km/h', 'Rainfall: ' + str(forecast['Rainfall']))
return render(request, 'weather/index.html', )
预期结果将显示来自数据库或函数输出的数据。目前它只打印来自 URL 的数据。我不知道从哪里开始。有什么想法吗?
【问题讨论】:
标签: python django-models django-templates django-views python-requests