0

I'm written a django web project and am using some API calls. I'd like to try and build in some mechanisms to handle slow and failed API calls. Specifically, I'd like to try the API call three times with increasing call times breaking the loop when the request is successful. What is a good way to handle this or is what I've put together acceptable? Below is the code I have in place now.

    for x in [0.5, 1, 5]: 
        try:
            r = requests.get(api_url, headers = headers, timeout=x)
            break
        except: 
            pass
M.javid
  • 6,387
  • 3
  • 41
  • 56
user4107395
  • 141
  • 7
  • is this [`requests`](http://www.python-requests.org/en/latest/) you are using? you probably want to `except` whatever timeout exception is raised explicitly, or at least use `except Exception` to avoid catching `SystemError`s or `KeyboardInterrupt`. See [here](http://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice) for more on why – lemonhead Aug 20 '15 at 02:43
  • also, the code as it is currently will catch the exception upon the final request timeout and continue on assuming `r` is a successful `Request`, which is probably not what you want... – lemonhead Aug 20 '15 at 02:45
  • http://migrateup.com/making-unreliable-apis-reliable-with-python/# – user4107395 Aug 20 '15 at 03:06

2 Answers2

0

You can use exceptions provided by requests itself to handle failed Api calls. You can use ConnectionError exception if a network problem occurs. Refer to this so post for more details. I am not pasting a link to requests docs and explaining every exception in detail since SO post given before have the answer for your question. An example code segment is given below

try:
    r = requests.get(url, params={'key': 'value'})
except requests.exceptions.ConnectionError as e:    
    print e
Community
  • 1
  • 1
cutteeth
  • 2,148
  • 3
  • 25
  • 45
0

This outlines the procedure I'm talking about. A single API request could end up being a little flaky.

migrateup.com/making-unreliable-apis-reliable-with-python/#

user4107395
  • 141
  • 7