Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requests — always call raise_for_status

Tags:

I'd like to remove the repeated x.raise_for_status() lines:

x = requests.get(url1) x.raise_for_status()  y = requests.delete(url2) y.raise_for_status()  z = requests.post(url3, data={'foo': 'bar'}) z.raise_for_status() 

How can I call raise_for_status() automatically?

like image 584
Max Malysh Avatar asked Aug 02 '17 20:08

Max Malysh


People also ask

What does Response Raise_for_status () do?

raise_for_status() returns an HTTPError object if an error has occurred during the process. It is used for debugging the requests module and is an integral part of Python requests.

How do you pass parameters in Python requests?

To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request. then https://somewebsite.com/?param1=value1&param2=value2 would be our final url.

How do you send POST data in requests?

The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.


1 Answers

Create a session with a hook:

session = requests.Session() session.hooks = {    'response': lambda r, *args, **kwargs: r.raise_for_status() }  x = session.get(url1) y = session.delete(url2) z = session.post(url3, data={'foo': 'bar'}) 
like image 154
Max Malysh Avatar answered Sep 20 '22 07:09

Max Malysh