【问题标题】:Django better way to avoid KeyError?Django 避免 KeyError 的更好方法?
【发布时间】:2022-06-10 20:37:09
【问题描述】:

我正在使用 Django 构建一个简单的天气应用程序。此应用程序允许用户输入城市名称,它会提供该城市的天气详细信息。我正在使用 API 来获取数据。

当用户输入空字符串或拼错城市时,我想避免 KeyError。我有点实现了我的目标,但我想知道是否有更简单的方法可以做到这一点。

这是我的代码:

from django.shortcuts import render
import requests
from datetime import datetime
import geonamescache  # Used for match checking


def home(request):

    # Checks for legitimate cities
    if 'search-city' in request.POST:
        gc = geonamescache.GeonamesCache()
        while request.POST['search-city'] != '':
            cities = str(gc.get_cities_by_name(request.POST['search-city']))
            if request.POST['search-city'] in cities:
                city = request.POST['search-city']
                break
            elif request.POST['search-city'] not in cities:
                city = 'Amsterdam'
                break

        while request.POST['search-city'] == '':
            city = 'Amsterdam'
            break

    # Call current weather
    URL = 'https://api.openweathermap.org/data/2.5/weather'
    API_KEY = 'c259be852acd2ef2ab8500d19f19890b'
    PAR = {

        'q': city,
        'appid': API_KEY,
        'units': 'metric'
    }

    req = requests.get(url=URL, params=PAR)
    res = req.json()

    city = res['name']
    description = res['weather'][0]['description']
    temp = res['main']['temp']
    icon = res['weather'][0]['icon']
    country = res['sys']['country']
    day = datetime.now().strftime("%d/%m/%Y %H:%M")

    weather_data = {

        'description': description,
        'temp': temp,
        'icon': icon,
        'day': day,
        'country': country,
        'city': city
    }

    return render(request, 'weatherapp/home.html', weather_data)

你们能告诉我你们是怎么做到的吗?谢谢!

【问题讨论】:

  • 可以使用.get()方法

标签: python django api keyerror


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2018-03-01
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 2014-09-08
相关资源
最近更新 更多