尝试搜索名称中带有 space 的城市的预报。 Openweathermap API Django Python

Try to search the forecast of cities with space in the name. Openweathermap API Django Python

我正在尝试解决名称中包含 space 的城市的问题。我环顾四周,但找不到符合我情况的东西。

这是代码:

    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 无法处理城市名称中的 space。

非常感谢。

只需使用urllib.parse.quote_plus:

import urllib.parse

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