I am a beginner and need a little support. Everything works in the application, but when in the form it typing "new york", "_" is missing in the url.
My code is
def index(request):
if request.method == 'POST':
city = request.POST['city']
if city == '':
return redirect('index')
res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=1b79ea7b1251b76ccda81d6bd').read()
json_data = json.loads(res)
datas = {
"country_code" : str(json_data['sys']['country']),
"cordinate": str(json_data['coord']['lon']) ''
str(json_data['coord']['lat']),
"temp": str(int(json_data['main']['temp']-273)) 'C',
"pressure" : str(json_data['main']['pressure']),
"humidity" : str(json_data['main']['humidity']),
}
In response receives "
InvalidURL at /
URL can't contain control characters. '/data/2.5/weather?q=bielsko biala&appid=1b79ea7b1251b76cc0b41a81d6bd' (found at least ' ')
I am looking for solutions on the Internet but I cannot solve it myself. Thank you very much for all your help
CodePudding user response:
You just need to replace spaces in city with the encoded values.
Try this:
import urllib.parse
res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={urllib.parse.quote(city)}&appid=1b79ea7b1251b76ccda81d6bd').read()
this is to encode city in the URL.