Mercurial > p > roundup > code
diff roundup/rate_limit.py @ 7590:5fbd3af526bd
fix: issue2551278 - datetime.datetime.utcnow deprecation.
We now use the timezone aware utc dates for python 3.11+.
But we have to make all the rest of the dates (datetime.min, unix
epoch date) timezon aware so we can subtract them. Also need to
marshall/unmarshall timezone aware iso formatted date strings.
| author | John Rouillard <rouilj@ieee.org> |
|---|---|
| date | Thu, 27 Jul 2023 00:53:36 -0400 |
| parents | 8f29e4ea05ce |
| children | 224ccb8b49ca |
line wrap: on
line diff
--- a/roundup/rate_limit.py Wed Jul 26 23:59:35 2023 -0400 +++ b/roundup/rate_limit.py Thu Jul 27 00:53:36 2023 -0400 @@ -6,6 +6,21 @@ 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 @@ -28,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 @@ -40,13 +55,13 @@ 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 @@ -100,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):
