【发布时间】:2021-08-12 22:55:33
【问题描述】:
我正在使用 API 制作一个简单的天气应用程序。 我收到错误:列表索引必须是整数或切片,而不是 str。我知道问题出在哪里,但我不知道如何解决。我的代码是:
from django.shortcuts import render
import urllib.request
import json
在此处创建您的视图。
def index(request):
if request.method == 'POST':
city = request.POST['city']
source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=5ba7df1f751428007642bf4e5f6c4c9a').read()
list_of_data = json.loads(source)
data = {
"country_code": str(list_of_data['sys']['country']),
"coordinate" : str(list_of_data['coord']['lon']) + ' '
+ str(list_of_data['coord']['lat']),
"temp" : str(list_of_data['main']['temp']) + 'k',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
"weather" : str(list_of_data['weather']['description']),
}
print(data)
else:
data = {}
return render(request, 'main/index.html', data)`
问题出在数据字典的最后一行。我不知道怎么写。请帮我解决这个问题。
【问题讨论】:
标签: python json python-3.x django django-views