什么python模块替换urllib2用于python 3和烧瓶?

Bru*_*ton 4 python json urllib

实际上,这个问题的措辞可能更好,因为要求实现这一目标的最佳实践.这很令人沮丧,因为这应该很容易.

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

我将列出相关的代码行,以显示我想要完成的任务.我使用python 3的最新版本的烧瓶.我不会列出模板文件,因为直到我尝试下载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
Run Code Online (Sandbox Code Playgroud)

任何意见,将不胜感激.
谢谢,布鲁斯

Vas*_*sif 5

您可以使用requests具有通用清洁界面的库来执行http操作.

该库的URL. http://www.python-requests.org/en/master/

你可以做

pip install requests
Run Code Online (Sandbox Code Playgroud)

在你的shell/cmd上安装.

在代码中,

import requests
response = requests.get(WEATHER_URL.format(query))
weather = response.json() # or something as easy as this.
Run Code Online (Sandbox Code Playgroud)