Skip to content

Commit bdf2b51

Browse files
authored
Merge pull request #199 from mathsman5133/cache_fix
Cache fix
2 parents 1c26f96 + 1259b2a commit bdf2b51

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

coc/errors.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,14 @@ class HTTPException(ClashOfClansException):
5353
__slots__ = ("response", "status", "message", "reason", "_data")
5454

5555
def _from_response(self, response, data):
56-
self.response = response
57-
self.status = response.status
56+
if isinstance(response, int):
57+
self.status = response
58+
self.response = None
59+
elif isinstance(response, ClientResponse):
60+
self.response = response
61+
self.status = response.status
62+
else:
63+
self.response = self.status = None
5864

5965
if isinstance(data, dict):
6066
self.reason = data.get("reason", "Unknown")
@@ -73,7 +79,7 @@ def _from_response(self, response, data):
7379
super().__init__(fmt.format(self))
7480

7581
def __init__(self, response=None, data=None):
76-
if isinstance(response, ClientResponse):
82+
if isinstance(response, (ClientResponse, int)):
7783
self._from_response(response, data)
7884
else:
7985
self.response = None

coc/http.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,20 @@ async def request(self, route, **kwargs):
264264
# the cache will be cleaned once it becomes stale / a new object is available from the api.
265265
if isinstance(cache, FIFO) and not self.client.realtime and not kwargs.get("ignore_cache", False):
266266
try:
267-
return cache[cache_control_key]
267+
data = cache[cache_control_key]
268+
status_code = data.get("status_code")
269+
if data.get("timestamp") and data.get("timestamp") + data.get("_response_retry", 0) < datetime.utcnow().timestamp():
270+
self._cache_remove(cache_control_key)
271+
elif not status_code or 200 <= status_code < 300:
272+
return data
273+
elif status_code == 400:
274+
raise InvalidArgument(400, data)
275+
elif status_code == 403:
276+
raise Forbidden(403, data)
277+
elif status_code == 404:
278+
raise NotFound(404, data)
279+
elif status_code == 503:
280+
raise Maintenance(503, data)
268281
except KeyError:
269282
pass
270283

@@ -281,7 +294,8 @@ async def request(self, route, **kwargs):
281294

282295
LOG.debug("API HTTP Request: %s", str(log_info))
283296
data = await json_or_text(response)
284-
297+
data["status_code"] = response.status
298+
data["timestamp"] = datetime.utcnow().timestamp()
285299
try:
286300
# set a callback to remove the item from cache once it's stale.
287301
delta = int(response.headers["Cache-Control"].strip("max-age=").strip("public max-age="))

0 commit comments

Comments
 (0)