Actually, the question might be better worded as a request for a best practice for accomplishing this. It is frustrating because this should be easy.
I am following a tutorial in the book Flask by Example. I am using the latest version of python 3. The urllib2 used in the text cannot be found for python 3. From the text, we need urllib2 to download the data, and urllib to correctly encode the parameters. Just one function, get_weather because I cannot find an updated approach that works.
I will list the relevant lines of code to show what I am trying to accomplish. I am using the latest version of flask with python 3. I won't list the template file, as the problem did not show up until I tried to download a json api.
So, the first changes to the file, include imports for urllib and json. The book is from 2015 when urllib2 was available. We are trying to get the Weather from openwheathermap.org. Since I could not find urllib2, I modified the book's code slightly.
I have
WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={}&APPID=myappid"
def get_weather(query):
query = urllib.parse.quote(query)
url = WEATHER_URL.format(query)
data = urllib.request.urlopen(url).read()
parsed = json.loads(str(data))
weather = None
if parsed.get('weather'):
weather = {'description': parsed['weather'][0]['description'],
'temperature': parsed['main']['temp'],
'city': parsed['name'],
'country': parsed['sys']['country']
}
return weather
Any advice would be appreciated.
Thanks,
Bruce