Skip to content

Commit 6315628

Browse files
committed
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.
1 parent 566dd9f commit 6315628

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

roundup/rate_limit.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,21 @@
66

77
from datetime import timedelta, datetime
88

9+
try:
10+
# used by python 3.11 and newer use tz aware dates
11+
from datetime import UTC
12+
dt_min = datetime.min.replace(tzinfo=UTC)
13+
# start of unix epoch
14+
dt_epoch = datetime(1970, 1, 1, tzinfo=UTC)
15+
fromisoformat = datetime.fromisoformat
16+
except ImportError:
17+
# python 2.7 and older than 3.11 - use naive dates
18+
dt_min = datetime.min
19+
dt_epoch = datetime(1970, 1, 1)
20+
def fromisoformat(date):
21+
# only for naive dates
22+
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f")
23+
924
from roundup.anypy.datetime_ import utcnow
1025

1126

@@ -28,7 +43,7 @@ def get_tat(self, key):
2843
if key in self.memory:
2944
return self.memory[key]
3045
else:
31-
return datetime.min
46+
return dt_min
3247

3348
def set_tat(self, key, tat):
3449
self.memory[key] = tat
@@ -40,13 +55,13 @@ def get_tat_as_string(self, key):
4055
if key in self.memory:
4156
return self.memory[key].isoformat()
4257
else:
43-
return datetime.min.isoformat()
58+
return dt_min.isoformat()
4459

4560
def set_tat_as_string(self, key, tat):
4661
# Take value as string and unmarshall:
4762
# YYYY-MM-DDTHH:MM:SS.mmmmmm
4863
# to datetime
49-
self.memory[key] = datetime.strptime(tat, "%Y-%m-%dT%H:%M:%S.%f")
64+
self.memory[key] = fromisoformat(tat)
5065

5166
def update(self, key, limit, testonly=False):
5267
'''Determine if the item associated with the key should be
@@ -100,7 +115,7 @@ def status(self, key, limit):
100115
seconds_to_tat = (tat - now).total_seconds()
101116
ret['X-RateLimit-Reset'] = str(max(seconds_to_tat, 0))
102117
ret['X-RateLimit-Reset-date'] = "%s" % tat
103-
ret['Now'] = str((now - datetime(1970, 1, 1)).total_seconds())
118+
ret['Now'] = str((now - dt_epoch).total_seconds())
104119
ret['Now-date'] = "%s" % now
105120

106121
if self.update(key, limit, testonly=True):

0 commit comments

Comments
 (0)