什么 python 模块替换了 urllib2 以便与 python 3 和 flask 一起使用?

What python module replaces urllib2 for use with python 3 and flask?

实际上,这个问题的措辞可能更好,因为它是对实现此目的的最佳实践的请求。令人沮丧,因为这应该很容易。

我正在学习 Flask by Example 一书中的教程。我用的是最新版的python 3.文中使用的urllib2找不到python 3.从文中我们需要urllib2来下载数据,需要urllib来正确编码参数.只有一个功能,get_weather 因为我找不到有效的更新方法。

我将列出相关的代码行以显示我正在努力完成的工作。我正在使用带有 python 3 的最新版本的 flask。我不会列出模板文件,因为直到我尝试下载 json api 时问题才出现。

因此,对文件的第一个更改包括对 urllib 和 json 的导入。这本书是 2015 年 urllib2 可用时的书。我们正在尝试从 openwheathermap.org 获取天气。由于找不到urllib2,我稍微修改了本书的代码。

我有

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

如有任何建议,我们将不胜感激。
谢谢, 布鲁斯

您可以使用 requests 界面更简洁的库来执行 http 操作。

URL 图书馆。 http://www.python-requests.org/en/master/

你可以做到

pip install requests

在你的 shell/cmd 上安装。

在代码中,

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