Which python module replaces urllib2 for use with python 3 and the jar?

Actually, the question can be better formulated as a request for best practice to achieve this. This is frustrating because it should be easy.

I follow the tutorial in Flask by Example. I am using the latest version of python 3. urlib2 used in the text cannot be found for python 3. From the text, we need urllib2 to load data and urllib to correctly encode the parameters. Only one get_weather function, because I cannot find an updated approach that works.

I will list the relevant lines of code to show what I'm trying to execute. I am using the latest version of the jar with python 3. I will not list the template file since the problem did not appear until I tried to download the json api.

So, the first changes to the file include import 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 changed the book code a bit.

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

+4
source share
1 answer

You can use a library requeststhat has a cleaner interface for performing http operations.

URL for the library. http://www.python-requests.org/en/master/

You can do

pip install requests

on your shell / cmd to install.

In code

import requests
response = requests.get(WEATHER_URL.format(query))
weather = response.json() # or something as easy as this.
+5
source

Source: https://habr.com/ru/post/1684334/


All Articles