From c60d80cbfc992b3cbaf303ae2e5f4f4c49fe028d Mon Sep 17 00:00:00 2001 From: Ben Darnell Date: Wed, 1 Nov 2023 21:40:54 -0400 Subject: [PATCH] web,demos: Remove more uses of deprecated datetime utc methods Add a simple test case to give us some basic coverage of this code path. Closes #3335 --- demos/blog/templates/feed.xml | 2 +- demos/s3server/s3server.py | 4 +++- tornado/test/web_test.py | 9 +++++++++ tornado/web.py | 3 ++- 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/demos/blog/templates/feed.xml b/demos/blog/templates/feed.xml index a98826c8..c63ef306 100644 --- a/demos/blog/templates/feed.xml +++ b/demos/blog/templates/feed.xml @@ -5,7 +5,7 @@ {% if len(entries) > 0 %} {{ max(e.updated for e in entries).strftime(date_format) }} {% else %} - {{ datetime.datetime.utcnow().strftime(date_format) }} + {{ datetime.datetime.now(datetime.timezone.utc).strftime(date_format) }} {% end %} http://{{ request.host }}/ diff --git a/demos/s3server/s3server.py b/demos/s3server/s3server.py index 5c5e6af2..b798c6b6 100644 --- a/demos/s3server/s3server.py +++ b/demos/s3server/s3server.py @@ -138,7 +138,9 @@ class RootHandler(BaseRequestHandler): buckets.append( { "Name": name, - "CreationDate": datetime.datetime.utcfromtimestamp(info.st_ctime), + "CreationDate": datetime.datetime.fromtimestamp( + info.st_ctime, datetime.timezone.utc + ), } ) self.render_xml({"ListAllMyBucketsResult": {"Buckets": {"Bucket": buckets}}}) diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index c8dce68c..fec66f39 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -1128,6 +1128,15 @@ class StaticFileTest(WebTestCase): self.assertTrue(b"Disallow: /" in response.body) self.assertEqual(response.headers.get("Content-Type"), "text/plain") + def test_static_files_cacheable(self): + # Test that the version parameter triggers cache-control headers. This + # test is pretty weak but it gives us coverage of the code path which + # was important for detecting the deprecation of datetime.utcnow. + response = self.fetch("/robots.txt?v=12345") + self.assertTrue(b"Disallow: /" in response.body) + self.assertIn("Cache-Control", response.headers) + self.assertIn("Expires", response.headers) + def test_static_compressed_files(self): response = self.fetch("/static/sample.xml.gz") self.assertEqual(response.headers.get("Content-Type"), "application/gzip") diff --git a/tornado/web.py b/tornado/web.py index 333f7368..03939647 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -2797,7 +2797,8 @@ class StaticFileHandler(RequestHandler): if cache_time > 0: self.set_header( "Expires", - datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time), + datetime.datetime.now(datetime.timezone.utc) + + datetime.timedelta(seconds=cache_time), ) self.set_header("Cache-Control", "max-age=" + str(cache_time))