Code

Ticket #5816: http_dates.2.diff

File http_dates.2.diff, 7.7 KB (added by SmileyChris, 6 years ago)
Line 
1Index: django/core/servers/basehttp.py
2===================================================================
3--- django/core/servers/basehttp.py     (revision 6594)
4+++ django/core/servers/basehttp.py     (working copy)
5@@ -9,13 +9,13 @@
6 
7 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
8 from types import ListType, StringType
9-from email.Utils import formatdate
10 import mimetypes
11 import os
12 import re
13 import sys
14 import time
15 import urllib
16+from django.utils.http import http_date
17 
18 __version__ = "0.1"
19 __all__ = ['WSGIServer','WSGIRequestHandler','demo_app']
20@@ -376,7 +376,7 @@
21                 self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
22                 if 'Date' not in self.headers:
23                     self._write(
24-                        'Date: %s\r\n' % (formatdate()[:26] + "GMT")
25+                        'Date: %s\r\n' % http_date()
26                     )
27                 if self.server_software and 'Server' not in self.headers:
28                     self._write('Server: %s\r\n' % self.server_software)
29Index: django/views/static.py
30===================================================================
31--- django/views/static.py      (revision 6594)
32+++ django/views/static.py      (working copy)
33@@ -7,13 +7,14 @@
34 import os
35 import posixpath
36 import re
37-import rfc822
38 import stat
39 import urllib
40+from email.utils import parsedate_tz, mktime_tz
41 
42 from django.template import loader
43 from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified
44 from django.template import Template, Context, TemplateDoesNotExist
45+from django.utils.http import http_date
46 
47 def serve(request, path, document_root=None, show_indexes=False):
48     """
49@@ -60,7 +61,7 @@
50     mimetype = mimetypes.guess_type(fullpath)[0]
51     contents = open(fullpath, 'rb').read()
52     response = HttpResponse(contents, mimetype=mimetype)
53-    response["Last-Modified"] = rfc822.formatdate(statobj[stat.ST_MTIME])
54+    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
55     return response
56 
57 DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
58@@ -119,8 +120,7 @@
59             raise ValueError
60         matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
61                            re.IGNORECASE)
62-        header_mtime = rfc822.mktime_tz(rfc822.parsedate_tz(
63-            matches.group(1)))
64+        header_mtime = mktime_tz(parsedate_tz(matches.group(1)))
65         header_len = matches.group(3)
66         if header_len and int(header_len) != size:
67             raise ValueError
68Index: django/contrib/sessions/middleware.py
69===================================================================
70--- django/contrib/sessions/middleware.py       (revision 6594)
71+++ django/contrib/sessions/middleware.py       (working copy)
72@@ -1,8 +1,7 @@
73+import time
74 from django.conf import settings
75 from django.utils.cache import patch_vary_headers
76-from email.Utils import formatdate
77-import datetime
78-import time
79+from django.utils.http import cookie_date
80 
81 TEST_COOKIE_NAME = 'testcookie'
82 TEST_COOKIE_VALUE = 'worked'
83@@ -30,13 +29,8 @@
84                     expires = None
85                 else:
86                     max_age = settings.SESSION_COOKIE_AGE
87-                    rfcdate = formatdate(time.time() + settings.SESSION_COOKIE_AGE)
88-
89-                    # Fixed length date must have '-' separation in the format
90-                    # DD-MMM-YYYY for compliance with Netscape cookie standard
91-                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + \
92-                              datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
93-
94+                    expires_time = time.time() + settings.SESSION_COOKIE_AGE
95+                    expires = cookie_date(expires_time)
96                 # Save the seesion data and refresh the client cookie.
97                 request.session.save()
98                 response.set_cookie(settings.SESSION_COOKIE_NAME,
99Index: django/utils/cache.py
100===================================================================
101--- django/utils/cache.py       (revision 6594)
102+++ django/utils/cache.py       (working copy)
103@@ -20,10 +20,10 @@
104 import md5
105 import re
106 import time
107-from email.Utils import formatdate
108 from django.conf import settings
109 from django.core.cache import cache
110 from django.utils.encoding import smart_str, iri_to_uri
111+from django.utils.http import http_date
112 
113 cc_delim_re = re.compile(r'\s*,\s*')
114 
115@@ -88,9 +88,9 @@
116     if not response.has_header('ETag'):
117         response['ETag'] = md5.new(response.content).hexdigest()
118     if not response.has_header('Last-Modified'):
119-        response['Last-Modified'] = formatdate()[:26] + "GMT"
120+        response['Last-Modified'] = http_date()
121     if not response.has_header('Expires'):
122-        response['Expires'] = formatdate(time.time() + cache_timeout)[:26] + "GMT"
123+        response['Expires'] = http_date(time.time() + cache_timeout)
124     patch_cache_control(response, max_age=cache_timeout)
125 
126 def add_never_cache_headers(response):
127Index: django/utils/http.py
128===================================================================
129--- django/utils/http.py        (revision 6594)
130+++ django/utils/http.py        (working copy)
131@@ -1,4 +1,5 @@
132 import urllib
133+from email.Utils import formatdate
134 from django.utils.encoding import smart_str, force_unicode
135 from django.utils.functional import allow_lazy
136 
137@@ -37,3 +38,29 @@
138             for k, v in query],
139         doseq)
140 
141+def cookie_date(epoch_seconds=None):
142+    """
143+    Format the time to ensure compatibility with Netscape's cookie standard.
144+
145+    Accepts a floating point number expressed in seconds since the epoch, in
146+    UTC - such as that outputted by time.time(). If set to None, defaults to the
147+    current time.
148+
149+    Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'.
150+    """
151+    rfcdate = formatdate(epoch_seconds)
152+    return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
153+
154+def http_date(epoch_seconds=None):
155+    """
156+    Format the time to match the RFC1123 date format as specified by HTTP
157+    RFC2616 section 3.3.1.
158+
159+    Accepts a floating point number expressed in seconds since the epoch, in
160+    UTC - such as that outputted by time.time(). If set to None, defaults to the
161+    current time.
162+
163+    Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
164+    """
165+    rfcdate = formatdate(epoch_seconds)
166+    return '%s GMT' % rfcdate[:25]
167Index: django/middleware/http.py
168===================================================================
169--- django/middleware/http.py   (revision 6594)
170+++ django/middleware/http.py   (working copy)
171@@ -1,4 +1,4 @@
172-from email.Utils import formatdate
173+from django.utils.http import http_date
174 
175 class ConditionalGetMiddleware(object):
176     """
177@@ -11,7 +11,7 @@
178     Also sets the Date and Content-Length response-headers.
179     """
180     def process_response(self, request, response):
181-        response['Date'] = formatdate()[:26] + "GMT"
182+        response['Date'] = http_date()
183         if not response.has_header('Content-Length'):
184             response['Content-Length'] = str(len(response.content))
185 
186Index: tests/regressiontests/text/tests.py
187===================================================================
188--- tests/regressiontests/text/tests.py (revision 6594)
189+++ tests/regressiontests/text/tests.py (working copy)
190@@ -27,6 +27,14 @@
191 >>> urlquote_plus(u'Paris & Orl\xe9ans', safe="&")
192 u'Paris+&+Orl%C3%A9ans'
193 
194+### cookie_date, http_date ###############################################
195+>>> from django.utils.http import cookie_date, http_date
196+>>> t = 1167616461.0
197+>>> cookie_date(t)
198+'Mon, 01-Jan-07 01:54:21 GMT'
199+>>> http_date(t)
200+'Mon, 01 Jan 2007 01:54:21 GMT'
201+
202 ### iri_to_uri ###########################################################
203 >>> from django.utils.encoding import iri_to_uri
204 >>> iri_to_uri(u'red%09ros\xe9#red')