python - Requests -- how to tell if you're getting a 404

ID : 20413

viewed : 21

Tags : pythonpython-requestspython

Top 5 Answer for python - Requests -- how to tell if you're getting a 404

vote vote

90

Look at the r.status_code attribute:

if r.status_code == 404:     # A 404 was issued. 

Demo:

>>> import requests >>> r = requests.get('http://httpbin.org/status/404') >>> r.status_code 404 

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404') >>> r.raise_for_status() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "requests/models.py", line 664, in raise_for_status     raise http_error requests.exceptions.HTTPError: 404 Client Error: NOT FOUND >>> r = requests.get('http://httpbin.org/status/200') >>> r.raise_for_status() >>> # no exception raised. 

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:     # successful response 

If you want to be more explicit, use if r.ok:.

vote vote

80

If your request is made inside another function, but you want to catch the error in a higher level, it is good to know that you can also get the status code directly from the exception. In my case I could not access the response since the HTTPError was raised before my function was able to pass on the response. I ended up doing the following:

try:      r = function_calling_request(the_request) except HTTPError as e:      if e.response.status_code == 404:           return do_stuff_if_not_found() 
vote vote

76

vote vote

62

GWT 2.0, which is supposed to come out sometime in the next few months, solves a lot of the issues discussed.

  • Create layouts using an html/xml like syntax
  • Dynamic Script Loading - only the essential JS will be downloaded initially. The rest will be downloaded as needed
  • In-Browser Hosted Mode - This might take care of the hosted mode speed issues discussed, among other benefits
  • "Compiler Optimizations" - Faster compilation, hopefully

GWT 2.0 Preview Video at Google I/O

vote vote

50

Not "unable to be overcome" but a bit of a pain for something basic.

Date handling:

GWT uses the deprecated java.util.Date which can lead to unexpected behaviour when dealing with dates on the client side. java.util.Calendar is not supported by GWT. More info here.

Related problem examples:

Top 3 video Explaining python - Requests -- how to tell if you're getting a 404

Related QUESTION?