msn
msn

Reputation: 457

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

In python, when a http request is invalid, response is None, in this case, how to get the response code from the response? The invalid request in my code are caused by two reasons, one is a invalid token, I expect to get 401 in this case, another reason is invalid parameter, I expect to get 400 in this case, but under both cases, response is always None and I'm not able to get the response code by calling response.getcode(), how to solve this?

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'

Upvotes: 1

Views: 3007

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

You can't get the status code when URLError is raised. Because when it is raised (ex: DNS couldn't resolve domain name), it means request hasn't been sent to server yet so there is no HTTP response generated.

In your scenario, (for 4xx HTTP status code), urllib2 throws HTTPError so you can derive the status code from it.

The documentation says:

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

Hope this helps.

Upvotes: 3

Related Questions