使用urllib,urllib2和request避免使用"Pyram of Doom"语法

alv*_*vas 2 python urllib request try-except

request为响应编写Python2和Python3以及依赖项代码很困难,因为它们的urlopen()函数和requests.get()函数返回不同的类型:

  • Python2 urllib.request.urlopen()返回一个http.client.HTTPResponse
  • Python3 urllib.urlopen(url)返回一个instance
  • 请求request.get(url)返回arequests.models.Response

为了支持Python2和Python3以及不想安装request依赖项的用户,我尝试了try-except导入和get_content()函数中的"金字塔末日" :

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.
Run Code Online (Sandbox Code Playgroud)

是否有其他方法可以实现返回读取内容和避免嵌套的相同结果try-except

mha*_*wke 7

您的用户使用有requests什么好处?简单地忽略requests和支持标准库函数更容易.通过这样导入,可以透明地完成其余的代码:

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
Run Code Online (Sandbox Code Playgroud)

从那时起,所有GET请求都可以发布urlopen(url).可以使用检索返回的数据read().

现在,如果您真的想继续提供requests支持,可以编写导入代码以及如下定义get_content():

try:
    import requests
    get_content = lambda url : requests.get(url).content
except ImportError:
    try:                   # Python 3
        from urllib.request import urlopen
    except ImportError:    # Python2
        from urllib2 import urlopen
    get_content = lambda url : urlopen(url).read()
Run Code Online (Sandbox Code Playgroud)