Mercurial > p > roundup > code
diff roundup/rate_limit.py @ 7692:8fb42f41ef10 issue2550923_computed_property
merge in default branch to see if ti clears a travis-ci build error on 2.7 python; default branch builds fine
| author | John Rouillard <rouilj@ieee.org> |
|---|---|
| date | Mon, 11 Sep 2023 00:10:29 -0400 |
| parents | 5fbd3af526bd |
| children | 224ccb8b49ca |
line wrap: on
line diff
--- a/roundup/rate_limit.py Mon Jul 10 17:31:34 2023 -0400 +++ b/roundup/rate_limit.py Mon Sep 11 00:10:29 2023 -0400 @@ -6,6 +6,23 @@ from datetime import timedelta, datetime +try: + # used by python 3.11 and newer use tz aware dates + from datetime import UTC + dt_min = datetime.min.replace(tzinfo=UTC) + # start of unix epoch + dt_epoch = datetime(1970, 1, 1, tzinfo=UTC) + fromisoformat = datetime.fromisoformat +except ImportError: + # python 2.7 and older than 3.11 - use naive dates + dt_min = datetime.min + dt_epoch = datetime(1970, 1, 1) + def fromisoformat(date): + # only for naive dates + return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f") + +from roundup.anypy.datetime_ import utcnow + class RateLimit: # pylint: disable=too-few-public-methods def __init__(self, count, period): @@ -26,7 +43,7 @@ if key in self.memory: return self.memory[key] else: - return datetime.min + return dt_min def set_tat(self, key, tat): self.memory[key] = tat @@ -38,19 +55,19 @@ if key in self.memory: return self.memory[key].isoformat() else: - return datetime.min.isoformat() + return dt_min.isoformat() def set_tat_as_string(self, key, tat): # Take value as string and unmarshall: # YYYY-MM-DDTHH:MM:SS.mmmmmm # to datetime - self.memory[key] = datetime.strptime(tat, "%Y-%m-%dT%H:%M:%S.%f") + self.memory[key] = fromisoformat(tat) def update(self, key, limit, testonly=False): '''Determine if the item associated with the key should be rejected given the RateLimit limit. ''' - now = datetime.utcnow() + now = utcnow() tat = max(self.get_tat(key), now) separation = (tat - now).total_seconds() max_interval = limit.period.total_seconds() - limit.inverse @@ -88,7 +105,7 @@ ) # status of current limit as of now - now = datetime.utcnow() + now = utcnow() current_count = int((limit.period - (tat - now)).total_seconds() / limit.inverse) @@ -98,7 +115,7 @@ seconds_to_tat = (tat - now).total_seconds() ret['X-RateLimit-Reset'] = str(max(seconds_to_tat, 0)) ret['X-RateLimit-Reset-date'] = "%s" % tat - ret['Now'] = str((now - datetime(1970, 1, 1)).total_seconds()) + ret['Now'] = str((now - dt_epoch).total_seconds()) ret['Now-date'] = "%s" % now if self.update(key, limit, testonly=True):
