From b2d86c6049d593f6263c10ba6e4fc7fa98279259 Mon Sep 17 00:00:00 2001 From: Dave Spano Date: Wed, 15 Nov 2017 18:22:13 -0500 Subject: [PATCH] Add self.retry_after to SparkRateLimitError class If one sets the wait_on_rate_limit to True in their CiscoSparkAPI class instantiation, they will hit an error telling them that retry_after is not an attribute of the SparkRateLimitError class. This is because the RestSession class checks for its existence when it catches the error at line 282 in restsession.py Error: File "/home/daspano/../ciscosparkapi/restsession.py", line 282, in request if self.wait_on_rate_limit and e.retry_after: AttributeError: 'SparkRateLimitError' object has no attribute 'retry_after' This commit adds that the retry_after attribute as an int, as my testing shows the Retry-After result always being an integer in seconds. Ex: -----------------------------------Response------------------------------------ 429 Too Many Requests Date: Wed, 15 Nov 2017 21:47:00 GMT Content-Type: application/json Content-Length: 182 Connection: keep-alive TrackingID: ROUTER_5A0CB5D2-B92F-01BB-7C3F-AC12D9227C3F Cache-Control: no-cache Retry-After: 194 Server: Redacted l5d-success-class: 1.0 Via: 1.1 linkerd content-encoding: gzip Strict-Transport-Security: max-age=63072000; includeSubDomains; preload --- ciscosparkapi/exceptions.py | 10 +++++++++- ciscosparkapi/restsession.py | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ciscosparkapi/exceptions.py b/ciscosparkapi/exceptions.py index eb1ce06..382f0cf 100644 --- a/ciscosparkapi/exceptions.py +++ b/ciscosparkapi/exceptions.py @@ -140,4 +140,12 @@ def __init__(self, response): class SparkRateLimitError(SparkApiError): """Cisco Spark Rate-Limit exceeded Error.""" - pass + + def __init__(self, response): + assert isinstance(response, requests.Response) + + # Set a sane default just incase Spark lets us down + self.retry_after = 200 + + if 'Retry-After' in response.headers.keys(): + self.retry_after = int(response.headers['Retry-After']) diff --git a/ciscosparkapi/restsession.py b/ciscosparkapi/restsession.py index b89bd46..06ce380 100644 --- a/ciscosparkapi/restsession.py +++ b/ciscosparkapi/restsession.py @@ -281,7 +281,7 @@ def request(self, method, url, erc, **kwargs): # Wait and retry if automatic rate-limit handling is enabled if self.wait_on_rate_limit and e.retry_after: logger.info("Received rate-limit message; " - "waiting {:0.0f} seconds." + "waiting {0} seconds." "".format(e.retry_after)) time.sleep(e.retry_after) continue