python-amazon-product-api / amazonproduct / contrib / retry.py

The default branch has multiple heads

import socket
import time
import urllib2

from amazonproduct.api import API

class RetryAPI (API):

    """
    API which will try up to TRIES times to fetch a result from Amazon should it run into a timeout.

    Based on work by Jerry Ji
    """

    #: Max number of tries before giving up
    TRIES = 5

    #: Delay between tries in seconds
    DELAY = 3

    #: Between each try the delay will be lengthened by this backoff multiplier
    BACKOFF = 1

    def _fetch(self, url):
        """
        Retrieves XML response from Amazon. In case of a timeout, it will try
        :const:`~RetryAPI.TRIES`` times before raising an error.
        """
        attempts = 0
        delay = self.DELAY

        while True:
            try:
                attempts += 1
                return API._fetch(self, url)
            except urllib2.URLError, e:

                # if a timeout occurred
                # wait for some time before trying again
                reason = getattr(e, 'reason', None)
                if isinstance(reason, socket.timeout) and attempts < self.TRIES:
                    time.sleep(delay)
                    delay *= self.BACKOFF
                    continue

                # otherwise reraise the original error
                raise
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.