Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retry on 5xx server errors #38

Open
NathanSmeltzer opened this issue Feb 10, 2023 · 1 comment
Open

Retry on 5xx server errors #38

NathanSmeltzer opened this issue Feb 10, 2023 · 1 comment

Comments

@NathanSmeltzer
Copy link

NathanSmeltzer commented Feb 10, 2023

After receiving a 504 GATEWAY_TIMEOUT from ShipStation's API, a retry with a backoff would improve stability.
Here a function that would solve this issue from this retries in requests guide:

def get_session(
    retries: int = 5,
    backoff_factor: float = 1,
    status_forcelist: list = [502, 503, 504],
) -> requests.Session:
    """Returns a requests session that retries on specific failures.
    also: https://stackoverflow.com/a/35636367/2469390
    https://www.coglib.com/~icordasc/blog/2014/12/retries-in-requests.html
    """
    session = requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

Then I think ShipStation.get would change to:

    def get(self, endpoint="", payload=None):
        url = "{}{}".format(self.url, endpoint)
       session = get_session()
        r = session.get(url, auth=(self.key, self.secret), params=payload)
        if self.debug:
            pprint.PrettyPrinter(indent=4).pprint(r.json())

        return r

And ShipStation.post to:

    def post(self, endpoint="", data=None):
        url = "{}{}".format(self.url, endpoint)
        headers = {"content-type": "application/json"}
       session = get_session()
        r = session.post(url, auth=(self.key, self.secret),
                          data=data, headers=headers)
        if self.debug:
            pprint.PrettyPrinter(indent=4).pprint(r.json())

       return r

And similar for put()

@NathanSmeltzer
Copy link
Author

PR submitted #39

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant