Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 04bc5b9

Browse files
committed
Issue #747320: Use email.utils.formatdate() to avoid code duplication
in BaseHTTPRequestHandler Initial patch by karlcow.
1 parent 0647ef0 commit 04bc5b9

2 files changed

Lines changed: 16 additions & 6 deletions

File tree

Lib/http/server.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
"SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
8888
]
8989

90+
import email.utils
9091
import html
9192
import http.client
9293
import io
@@ -566,12 +567,7 @@ def date_time_string(self, timestamp=None):
566567
"""Return the current date and time formatted for a message header."""
567568
if timestamp is None:
568569
timestamp = time.time()
569-
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
570-
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
571-
self.weekdayname[wd],
572-
day, self.monthname[month], year,
573-
hh, mm, ss)
574-
return s
570+
return email.utils.formatdate(timestamp, usegmt=True)
575571

576572
def log_date_time_string(self):
577573
"""Return the current time formatted for logging."""

Lib/test/test_httpservers.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import html
1818
import http.client
1919
import tempfile
20+
import time
2021
from io import BytesIO
2122

2223
import unittest
@@ -873,6 +874,19 @@ def handle_one_request():
873874
self.handler.handle()
874875
self.assertRaises(StopIteration, next, close_values)
875876

877+
def test_date_time_string(self):
878+
now = time.time()
879+
# this is the old code that formats the timestamp
880+
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
881+
expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
882+
self.handler.weekdayname[wd],
883+
day,
884+
self.handler.monthname[month],
885+
year, hh, mm, ss
886+
)
887+
self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
888+
889+
876890
class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
877891
""" Test url parsing """
878892
def setUp(self):

0 commit comments

Comments
 (0)