How to access server response when Python requests library encounters the retry limit

2024/9/20 1:00:42

I am using the Python requests library to implement retry logic. Here is a simple script I made to reproduce the problem that I am having. In the case where we run out of retries, I would like to be able to log at least one of the responses from the server to help debugging. However, it is not clear to me how to access that information. Of course, I could implement retries in some other way to accomplish my goal, but it seemed like this wasn't that much of an edge case and I would be surprised to find out that requests did not support my use case.

I have looked at the requests.exceptions.RetryError, the requests.packages.urllib3.exceptions.MaxRetryError that it wraps, and the requests.packages.urllib3.exceptions.ResponseError that that wraps all to no avail.

Am I missing something?

#!/usr/bin/env pythonimport requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests.exceptions import RetryErrordef main():retry_policy = Retry(total=3,status_forcelist=[418])session = requests.Session()session.mount('http://', HTTPAdapter(max_retries=retry_policy))try:session.get('http://httpbin.org/status/418')except RetryError as retry_error:print retry_errorprint retry_error.response is Noneif __name__ == '__main__':main()

$ python test.py

HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /status/418 (Caused by ResponseError('too many 418 error responses',))True
Answer

Checking out the urllib3 source, I discovered that the Retry object takes a named parameter called raise_on_status. True is the default. When set to False, running into the retry limit causes a response to be returned instead of an exception being thrown. The code below shows me causing an HTTPError (containing the Response) to be thrown by using the raise_for_status method on the Response, but one could just as easily use the Response directly.

#!/usr/bin/env pythonimport requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests.exceptions import HTTPErrordef main():retry_policy = Retry(total=3,status_forcelist=[418],raise_on_status=False)session = requests.Session()session.mount('http://', HTTPAdapter(max_retries=retry_policy))try:response = session.get('http://httpbin.org/status/418')response.raise_for_status()except HTTPError as e:print e.response.status_codeprint e.response.contentif __name__ == '__main__':main()

$ python test.py

418-=[ teapot ]=-_...._.'  _ _ `.
| ."` ^ `". _,
\_;`"---"`|//|       ;/\_     _/`"""`
https://en.xdnf.cn/q/72389.html

Related Q&A

Matplotlib patch with holes

The following code works. The problem is I dont know exactly why it works. The code draws a circle patch (using PathPatch) with a triangle cutout from the centre. My guess is that the inner triangle is…

Convert sha256 digest to UUID in python

Given a sha256 hash of a str in python: import hashlibhash = hashlib.sha256(foobar.encode(utf-8))How can the hash be converted to a UUID? Note: there will obviously be a many-to-one mapping of hexdige…

Drag and Drop QLabels with PyQt5

Im trying to drag and drop a Qlabel on another Qlabel with PyQt5:from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QHBoxLayout, QVBoxLayout, QGridLayout,QFrame, QCo…

replace block within {{ super() }}

I have a base template which includes a block for the default <head> content. Within the head block, theres a block for the <title>.For example, in the base file I would have:<head>{%…

Change Timezone for Date object Python

Hello I am using Pythonanywhere and when I call from datetime import *print date.today().dayIt is printing a different day than the day it is where I live (Austin, Texas). I figured it is because there…

Multiprocessing Pool - how to cancel all running processes if one returns the desired result?

Given the following Python code: import multiprocessingdef unique(somelist):return len(set(somelist)) == len(somelist)if __name__ == __main__:somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5],…

Pandas: Product of specific columns

Finding the product of all columns in a dataframe is easy:df[Product] = df.product(axis=1)How can I specify which column names (not column numbers) to include in the product operation?From the help pa…

instagram.bind.InstagramClientError: Unable to parse response, not valid JSON

Made myself a simple Instagram client to make authenticated requests to their API. However, running it keeps throwing the following errorTraceback (most recent call last):File "request-ig-data.py&…

Using jinja to send data to Javascript

I have Python code, in which Im using jinja to send data to a template in Flask. I can access the code just find in HTML, but when I try displaying the data in Javascript, it doesnt work. For example, …

celery: Substantial drift from

I have quite a problem with celery on my distribted system. I have couple of machines among different localizations and Ive got a lot of warnings in my log files like:"Substantial drift from celer…