I'm try to resolve the problem of the cities that have space in the name. I look around a bit but i couldn't find anything that match my case.
This is the code:
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)
If anyone know how to resolve this problem will be great. I'd like also understand why the URL can't handle the space in the city name.
Thank you very much.
Just use urllib.parse.quote_plus
:
import urllib.parse
city = urllib.parse.quote_plus(request.POST['city'])