Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requests — how to tell if you're getting a success message?

My question is closely related to this one.

I'm using the Requests library to hit an HTTP endpoint. I want to check if the response is a success.

I am currently doing this:

r = requests.get(url) if 200 <= response.status_code <= 299:     # Do something here! 

Instead of doing that ugly check for values between 200 and 299, is there a shorthand I can use?

like image 656
Saqib Ali Avatar asked Nov 06 '17 19:11

Saqib Ali


People also ask

What is the success response for GET request?

Successful responses The request succeeded. The result meaning of "success" depends on the HTTP method: GET : The resource has been fetched and transmitted in the message body. HEAD : The representation headers are included in the response without any message body.

How do I get response to text in Python?

text returns the content of the response, in unicode. Basically, it refers to Binary Response content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.


Video Answer


1 Answers

The response has an ok property. Use that:

if response.ok:     ... 

The implementation is just a try/except around Response.raise_for_status, which is itself checks the status code.

@property def ok(self):     """Returns True if :attr:`status_code` is less than 400, False if not.      This attribute checks if the status code of the response is between     400 and 600 to see if there was a client error or a server error. If     the status code is between 200 and 400, this will return True. This     is **not** a check to see if the response code is ``200 OK``.     """     try:         self.raise_for_status()     except HTTPError:         return False     return True 
like image 160
wim Avatar answered Sep 28 '22 11:09

wim