【问题标题】:Try to search the forecast of cities with space in the name. Openweathermap API Django Python尝试搜索名称中带有空格的城市的预测。 Openweathermap API Django Python
【发布时间】:2021-07-22 18:45:12
【问题描述】:

我正在尝试解决名称中有空格的城市的问题。我环顾四周,但找不到与我的情况相符的任何东西。

这是代码:

    def search(request):
    if request.method == 'POST':
        city = request.POST['city']

        source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+ city +'&units=metric&appid=API_KEY').read()

        list_of_data = json.loads(source)
        # print(list_of_data)

        wind_speed = list_of_data['wind']['speed']
        wind_gust =  list_of_data['wind']['gust']



#function for convert the wind speed in knot
        def wind_converter(w,g):
            knots = 2
            kt = (int(w)) + (int(g))* knots
            return kt

        wind_response = wind_converter(wind_speed,wind_gust)

#function for convert deg in cardinal direction

        wind_direction = list_of_data['wind']['deg']

        def degrees_to_cardinal(d):

            dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
            ix = round(d / (360. / len(dirs)))
            return dirs[ix % len(dirs)]

        wind_direction = degrees_to_cardinal(wind_direction)

        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']) + ' °C',
            "pressure": str(list_of_data['main']['pressure']),
            "humidity": str(list_of_data['main']['humidity']),
            'main': str(list_of_data['weather'][0]['main']),
            'description': str(list_of_data['weather'][0]['description']),
            'icon': list_of_data['weather'][0]['icon'],
            'wind_speed':list_of_data['wind']['speed'],
            'direction':list_of_data['wind']['deg'],
            'wind_gust':list_of_data['wind']['gust'],
            'wind_response':wind_response,
            'wind_direction':wind_direction,
    

        }
        print(data)
    else:
        data = {}
    return render(request, "WindApp/wind_search.html", data)

如果有人知道如何解决这个问题,那就太好了。 我也想了解为什么 URL 不能处理城市名称中的空格。

非常感谢。

【问题讨论】:

    标签: python django api weather openweathermap


    【解决方案1】:

    只需使用urllib.parse.quote_plus:

    import urllib.parse
    
    city = urllib.parse.quote_plus(request.POST['city'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 2012-03-07
      • 1970-01-01
      • 2016-01-31
      • 2012-08-15
      • 1970-01-01
      • 2013-10-17
      • 2021-05-18
      相关资源
      最近更新 更多