Skip to content

Commit 93544ed

Browse files
pgansslefrostming
andauthoredJun 1, 2023
fix: Remove use of utcnow (#290)
* Remove utcnow This removes the use of utcnow to avoid deprecation warnings, though ideally this would be fixed instead by switching over to using aware datetimes instead. * Use aware datetimes --------- Co-authored-by: Frost Ming <mianghong@gmail.com>
1 parent 2b696f6 commit 93544ed

File tree

4 files changed

+20
-9
lines changed

4 files changed

+20
-9
lines changed
 

‎cachecontrol/caches/redis_cache.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from __future__ import division
66

7-
from datetime import datetime
7+
from datetime import datetime, timezone
88
from typing import TYPE_CHECKING, Optional, Union
99

1010
from cachecontrol.cache import BaseCache
@@ -26,7 +26,10 @@ def set(
2626
if not expires:
2727
self.conn.set(key, value)
2828
elif isinstance(expires, datetime):
29-
delta = expires - datetime.utcnow()
29+
now_utc = datetime.now(timezone.utc)
30+
if expires.tzinfo is None:
31+
now_utc = now_utc.replace(tzinfo=None)
32+
delta = expires - now_utc
3033
self.conn.setex(key, int(delta.total_seconds()), value)
3134
else:
3235
self.conn.setex(key, expires, value)

‎cachecontrol/heuristics.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import calendar
66
import time
7-
from datetime import datetime, timedelta
7+
from datetime import datetime, timedelta, timezone
88
from email.utils import formatdate, parsedate, parsedate_tz
99
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional
1010

@@ -15,7 +15,7 @@
1515

1616

1717
def expire_after(delta: timedelta, date: Optional[datetime] = None) -> datetime:
18-
date = date or datetime.utcnow()
18+
date = date or datetime.now(timezone.utc)
1919
return date + delta
2020

2121

@@ -67,7 +67,7 @@ def update_headers(self, response: "HTTPResponse") -> Dict[str, str]:
6767

6868
if "expires" not in response.headers:
6969
date = parsedate(response.headers["date"])
70-
expires = expire_after(timedelta(days=1), date=datetime(*date[:6]))
70+
expires = expire_after(timedelta(days=1), date=datetime(*date[:6], tzinfo=timezone.utc)) # type: ignore[misc]
7171
headers["expires"] = datetime_to_header(expires)
7272
headers["cache-control"] = "public"
7373
return headers

‎tests/test_expires_heuristics.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import calendar
66
import time
7-
from datetime import datetime
7+
from datetime import datetime, timezone
88
from email.utils import formatdate, parsedate
99
from pprint import pprint
1010
from unittest.mock import Mock
@@ -157,7 +157,9 @@ def test_last_modified_is_used(self):
157157
resp = DummyResponse(200, {"Date": self.now, "Last-Modified": self.week_ago})
158158
modified = self.heuristic.update_headers(resp)
159159
assert ["expires"] == list(modified.keys())
160-
assert datetime(*parsedate(modified["expires"])[:6]) > datetime.now()
160+
161+
expected = datetime(*parsedate(modified["expires"])[:6], tzinfo=timezone.utc)
162+
assert expected > datetime.now(timezone.utc)
161163

162164
def test_last_modified_is_not_used_when_cache_control_present(self):
163165
resp = DummyResponse(
@@ -185,7 +187,8 @@ def test_last_modified_is_used_when_cache_control_public(self):
185187
)
186188
modified = self.heuristic.update_headers(resp)
187189
assert ["expires"] == list(modified.keys())
188-
assert datetime(*parsedate(modified["expires"])[:6]) > datetime.now()
190+
expected = datetime(*parsedate(modified["expires"])[:6], tzinfo=timezone.utc)
191+
assert expected > datetime.now(timezone.utc)
189192

190193
def test_warning_not_added_when_response_more_recent_than_24_hours(self):
191194
resp = DummyResponse(200, {"Date": self.now, "Last-Modified": self.week_ago})

‎tests/test_storage_redis.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#
33
# SPDX-License-Identifier: Apache-2.0
44

5-
from datetime import datetime
5+
from datetime import datetime, timezone
66
from unittest.mock import Mock
77

88
from cachecontrol.caches import RedisCache
@@ -17,6 +17,11 @@ def test_set_expiration_datetime(self):
1717
self.cache.set("foo", "bar", expires=datetime(2014, 2, 2))
1818
assert self.conn.setex.called
1919

20+
def test_set_expiration_datetime_aware(self):
21+
self.cache.set("foo", "bar",
22+
expires=datetime(2014, 2, 2, tzinfo=timezone.utc))
23+
assert self.conn.setex.called
24+
2025
def test_set_expiration_int(self):
2126
self.cache.set("foo", "bar", expires=600)
2227
assert self.conn.setex.called

0 commit comments

Comments
 (0)
Please sign in to comment.