Python TypeError: индексы списка должны быть целыми числами или срезами, а не str, Django 3.1 ЗАКРЫТО - PullRequest
0 голосов
/ 05 августа 2020
    city_info = {
    'city': city,
    'temp': res['main']['temp'],
    'weatherDescription': res['weather']['description'],
    'icon': res['weather']['icon'],
    'windSpeed': res['wind']['speed'],
}

Почему, когда я вызываю объект «погода» API OpenWetherMap, я получаю сообщение об ошибке:

TypeError: list indices must be integers or slices, not str

Я использую Python 3.8.2 и Django 3.1

Полный код, например:

from django.shortcuts import render
import requests

def index(request):
    # This is MINE API key! You can change it to yours, if you need it.
    apiKey = '8bf70752121d2f2366e66d73f3445966'
    url = 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + apiKey 

    city = 'Washington'
    res = requests.get(url.format(city)).json()

    city_info = {
        'city': city,
        'temp': res['main']['temp'],
        'weatherDescription': res['weather']['description'],
        'icon': res['weather']['icon'],
        'windSpeed': res['wind']['speed'],
    }

    context = {'info': city_info}

    return render(request, 'weather/index.html', context)

1 Ответ

0 голосов
/ 05 августа 2020

res['weather'] - это список, содержащий словарь, поэтому просто сделайте это:

city_info = {
    'city': city,
    'temp': res['main']['temp'],
    'weatherDescription': res['weather'][0]['description'],
    'icon': res['weather'][0]['icon'],
    'windSpeed': res['wind']['speed'],
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...