python,当http响应为None时,如何获取响应码

python, when http response is None, how to get a response code

在python中,当http请求无效时,response为None,这种情况下,如何从response中获取response code?我代码中的无效请求是由两个原因引起的,一个是无效令牌,我希望在这种情况下得到 401,另一个原因是无效参数,我希望在这种情况下得到 400,但是在这两种情况下,响应总是 None 并且我无法通过调用 response.getcode() 来获取响应代码,如何解决这个问题?

req = urllib2.Request(url)
response = None
try: response = urllib2.urlopen(req)
except urllib2.URLError as e:
    res_code = response.getcode() #AttributeError: 'NoneType' object has no attribute 'getcode'

引发URLError时无法获取状态码。因为当它被引发时(例如:DNS 无法解析域名),这意味着请求还没有发送到服务器,所以没有生成 HTTP 响应。

在您的场景中,(对于 4xx HTTP 状态代码),urllib2 抛出 HTTPError 以便您可以从中导出状态代码。

documentation 说:

code

An HTTP status code as defined in RFC 2616. This numeric value corresponds to a value found in the dictionary of codes as found in BaseHTTPServer.BaseHTTPRequestHandler.responses.


import urllib2

request = urllib2.Request(url)
try: 
    response = urllib2.urlopen(request)
    res_code = response.code
except urllib2.HTTPError as e:
    res_code = e.code

希望这对您有所帮助。