@robocop45
Only python

KeyError at / 'main' — как исправить?

Ошибка:
KeyError at /
'main'
Request Method:	GET
Request URL:	http://127.0.0.1:8000/
Django Version:	4.1.3
Exception Type:	KeyError
Exception Value:	
'main'
Exception Location:	C:\django-sites\trydj\weatherapp\weather\views.py, line 33, in index
Raised during:	weather.views.index
Python Executable:	C:\django-sites\trydj\venv\Scripts\python.exe
Python Version:	3.8.10
Python Path:	
['C:\\django-sites\\trydj\\weatherapp',
 'C:\\Users\\Константин\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
 'C:\\Users\\Константин\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
 'C:\\Users\\Константин\\AppData\\Local\\Programs\\Python\\Python38\\lib',
 'C:\\Users\\Константин\\AppData\\Local\\Programs\\Python\\Python38',
 'C:\\django-sites\\trydj\\venv',
 'C:\\django-sites\\trydj\\venv\\lib\\site-packages']
Server time:	Sat, 05 Nov 2022 16:59:04 +0000
Traceback Switch to copy-and-paste view
C:\django-sites\trydj\venv\lib\site-packages\django\core\handlers\exception.py, line 55, in inner
                response = get_response(request) …
Local vars
C:\django-sites\trydj\venv\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
C:\django-sites\trydj\weatherapp\weather\views.py, line 33, in index
            'temp': res["main"]["temp"],


Делаю запрос через google и отдается вот такой словарь, где имя 'main' имеется
Скриншот фрагмента кода удален модератором.

views.py
import requests
from django.shortcuts import render

# Create your views here.
from requests import RequestException

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'TE': 'Trailers',
}

params = (
    ('__blob', 'publicationFile'),
)


def index(request):
    appid = 'cbf515c1138c3671ac09ee0b4b8e8da0'
    url = 'https://api.openweathermap.org/data/2.5/weather?q={}%units=metric&appid=' + appid

    city = 'London'
    try:
        res = requests.get(url.format(city), headers=headers, params=params, verify=False).json()
        # print(res.status_code)
        # print(res.text)

        city_info = {
            'city': city,
            'temp': res["main"]["temp"],
            'icon': res["weather"][0]["icon"]
        }

        context = {
            'info': city_info
        }
    except RequestException:
        print('Ошибка сети')

    return render(request, 'weather/index.html', context)
  • Вопрос задан
  • 280 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Wispik
Так трудно print(res) сделать и посмотреть что апи возвращает?
{'cod': '404', 'message': 'city not found'}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы