问题描述
我正在尝试解决名称中有空格的城市问题。我环顾四周,但找不到与我的情况相符的任何东西。
这是代码:
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 无法处理城市名称中的空格。
非常感谢。
解决方法
import urllib.parse
city = urllib.parse.quote_plus(request.POST['city'])