Changeset 6638
- Timestamp:
- 11/02/07 21:16:27 (10 months ago)
- Files:
-
- django/branches/queryset-refactor/django/contrib/sessions/middleware.py (modified) (3 diffs)
- django/branches/queryset-refactor/django/core/servers/basehttp.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/middleware/http.py (modified) (3 diffs)
- django/branches/queryset-refactor/django/newforms/models.py (modified) (10 diffs)
- django/branches/queryset-refactor/django/utils/cache.py (modified) (9 diffs)
- django/branches/queryset-refactor/django/utils/http.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/views/static.py (modified) (3 diffs)
- django/branches/queryset-refactor/docs/cache.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/email.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/form_preview.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/modpython.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/testing.txt (modified) (1 diff)
- django/branches/queryset-refactor/tests/regressiontests/text/tests.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/queryset-refactor/django/contrib/sessions/middleware.py
r6597 r6638 1 import time 2 1 3 from django.conf import settings 2 4 from django.utils.cache import patch_vary_headers 3 from email.Utils import formatdate 4 import datetime 5 import time 5 from django.utils.http import cookie_date 6 6 7 7 TEST_COOKIE_NAME = 'testcookie' … … 11 11 12 12 def process_request(self, request): 13 engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 14 request.session = engine.SessionStore(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) 13 engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 14 session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) 15 request.session = engine.SessionStore(session_key) 15 16 16 17 def process_response(self, request, response): … … 31 32 else: 32 33 max_age = settings.SESSION_COOKIE_AGE 33 rfcdate = formatdate(time.time() + settings.SESSION_COOKIE_AGE) 34 35 # Fixed length date must have '-' separation in the format 36 # DD-MMM-YYYY for compliance with Netscape cookie standard 37 expires = datetime.datetime.strftime(datetime.datetime.utcnow() + \ 38 datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT") 39 34 expires_time = time.time() + settings.SESSION_COOKIE_AGE 35 expires = cookie_date(expires_time) 40 36 # Save the seesion data and refresh the client cookie. 41 37 request.session.save() django/branches/queryset-refactor/django/core/servers/basehttp.py
r5721 r6638 10 10 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 11 11 from types import ListType, StringType 12 from email.Utils import formatdate13 12 import mimetypes 14 13 import os 15 14 import re 16 15 import sys 17 import time18 16 import urllib 17 18 from django.utils.http import http_date 19 19 20 20 __version__ = "0.1" … … 377 377 if 'Date' not in self.headers: 378 378 self._write( 379 'Date: %s\r\n' % (formatdate()[:26] + "GMT")379 'Date: %s\r\n' % http_date() 380 380 ) 381 381 if self.server_software and 'Server' not in self.headers: django/branches/queryset-refactor/django/middleware/http.py
r6466 r6638 1 from email.Utils import formatdate1 from django.utils.http import http_date 2 2 3 3 class ConditionalGetMiddleware(object): … … 12 12 """ 13 13 def process_response(self, request, response): 14 response['Date'] = formatdate()[:26] + "GMT"14 response['Date'] = http_date() 15 15 if not response.has_header('Content-Length'): 16 16 response['Content-Length'] = str(len(response.content)) … … 24 24 25 25 if response.has_header('Last-Modified'): 26 last_mod = response['Last-Modified']27 26 if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE', None) 28 27 if if_modified_since == response['Last-Modified']: django/branches/queryset-refactor/django/newforms/models.py
r5819 r6638 7 7 from django.utils.encoding import smart_unicode 8 8 9 10 9 from util import ValidationError 11 10 from forms import BaseForm, SortedDictFromList … … 18 17 ) 19 18 20 def save_instance(form, instance, fields=None, fail_message='saved', commit=True): 19 def save_instance(form, instance, fields=None, fail_message='saved', 20 commit=True): 21 21 """ 22 22 Saves bound Form ``form``'s cleaned_data into model instance ``instance``. … … 28 28 opts = instance.__class__._meta 29 29 if form.errors: 30 raise ValueError("The %s could not be %s because the data didn't validate." % (opts.object_name, fail_message)) 30 raise ValueError("The %s could not be %s because the data didn't" 31 " validate." % (opts.object_name, fail_message)) 31 32 cleaned_data = form.cleaned_data 32 33 for f in opts.fields: 33 if not f.editable or isinstance(f, models.AutoField) or not f.name in cleaned_data: 34 if not f.editable or isinstance(f, models.AutoField) \ 35 or not f.name in cleaned_data: 34 36 continue 35 37 if fields and f.name not in fields: 36 38 continue 37 f.save_form_data(instance, cleaned_data[f.name]) 38 # Wrap up the saving of m2m data as a function 39 f.save_form_data(instance, cleaned_data[f.name]) 40 # Wrap up the saving of m2m data as a function. 39 41 def save_m2m(): 40 42 opts = instance.__class__._meta … … 46 48 f.save_form_data(instance, cleaned_data[f.name]) 47 49 if commit: 48 # If we are committing, save the instance and the m2m data immediately 50 # If we are committing, save the instance and the m2m data immediately. 49 51 instance.save() 50 52 save_m2m() 51 53 else: 52 # We're not committing. Add a method to the form to allow deferred 53 # saving of m2m data 54 # We're not committing. Add a method to the form to allow deferred 55 # saving of m2m data. 54 56 form.save_m2m = save_m2m 55 57 return instance 56 58 57 59 def make_model_save(model, fields, fail_message): 58 " Returns the save() method for a Form."60 """Returns the save() method for a Form.""" 59 61 def save(self, commit=True): 60 62 return save_instance(self, model(), fields, fail_message, commit) 61 63 return save 62 64 63 65 def make_instance_save(instance, fields, fail_message): 64 " Returns the save() method for a Form."66 """Returns the save() method for a Form.""" 65 67 def save(self, commit=True): 66 68 return save_instance(self, instance, fields, fail_message, commit) 67 69 return save 68 70 69 def form_for_model(model, form=BaseForm, fields=None, formfield_callback=lambda f: f.formfield()): 71 def form_for_model(model, form=BaseForm, fields=None, 72 formfield_callback=lambda f: f.formfield()): 70 73 """ 71 74 Returns a Form class for the given Django model class. … … 88 91 field_list.append((f.name, formfield)) 89 92 base_fields = SortedDictFromList(field_list) 90 return type(opts.object_name + 'Form', (form,), 91 {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')}) 92 93 def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 93 return type(opts.object_name + 'Form', (form,), 94 {'base_fields': base_fields, '_model': model, 95 'save': make_model_save(model, fields, 'created')}) 96 97 def form_for_instance(instance, form=BaseForm, fields=None, 98 formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 94 99 """ 95 100 Returns a Form class for the given Django model instance. … … 116 121 base_fields = SortedDictFromList(field_list) 117 122 return type(opts.object_name + 'InstanceForm', (form,), 118 {'base_fields': base_fields, '_model': model, 'save': make_instance_save(instance, fields, 'changed')}) 123 {'base_fields': base_fields, '_model': model, 124 'save': make_instance_save(instance, fields, 'changed')}) 119 125 120 126 def form_for_fields(field_list): 121 "Returns a Form class for the given list of Django database field instances." 122 fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list if f.editable]) 127 """ 128 Returns a Form class for the given list of Django database field instances. 129 """ 130 fields = SortedDictFromList([(f.name, f.formfield()) 131 for f in field_list if f.editable]) 123 132 return type('FormForFields', (BaseForm,), {'base_fields': fields}) 124 133 125 134 class QuerySetIterator(object): 126 135 def __init__(self, queryset, empty_label, cache_choices): 127 self.queryset, self.empty_label, self.cache_choices = queryset, empty_label, cache_choices 136 self.queryset = queryset 137 self.empty_label = empty_label 138 self.cache_choices = cache_choices 128 139 129 140 def __iter__(self): … … 137 148 138 149 class ModelChoiceField(ChoiceField): 139 " A ChoiceField whose choices are a model QuerySet."150 """A ChoiceField whose choices are a model QuerySet.""" 140 151 # This class is a subclass of ChoiceField for purity, but it doesn't 141 152 # actually use any of ChoiceField's implementation. 153 142 154 def __init__(self, queryset, empty_label=u"---------", cache_choices=False, 143 required=True, widget=Select, label=None, initial=None, help_text=None): 155 required=True, widget=Select, label=None, initial=None, 156 help_text=None): 144 157 self.queryset = queryset 145 158 self.empty_label = empty_label … … 161 174 # self.choices is accessed) so that we can ensure the QuerySet has not 162 175 # been consumed. 163 return QuerySetIterator(self.queryset, self.empty_label, self.cache_choices) 176 return QuerySetIterator(self.queryset, self.empty_label, 177 self.cache_choices) 164 178 165 179 def _set_choices(self, value): … … 178 192 value = self.queryset.model._default_manager.get(pk=value) 179 193 except self.queryset.model.DoesNotExist: 180 raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.')) 194 raise ValidationError(ugettext(u'Select a valid choice. That' 195 u' choice is not one of the' 196 u' available choices.')) 181 197 return value 182 198 183 199 class ModelMultipleChoiceField(ModelChoiceField): 184 " A MultipleChoiceField whose choices are a model QuerySet."200 """A MultipleChoiceField whose choices are a model QuerySet.""" 185 201 hidden_widget = MultipleHiddenInput 202 186 203 def __init__(self, queryset, cache_choices=False, required=True, 187 widget=SelectMultiple, label=None, initial=None, help_text=None): 188 super(ModelMultipleChoiceField, self).__init__(queryset, None, cache_choices, 189 required, widget, label, initial, help_text) 204 widget=SelectMultiple, label=None, initial=None, 205 help_text=None): 206 super(ModelMultipleChoiceField, self).__init__(queryset, None, 207 cache_choices, required, widget, label, initial, help_text) 190 208 191 209 def clean(self, value): … … 201 219 obj = self.queryset.model._default_manager.get(pk=val) 202 220 except self.queryset.model.DoesNotExist: 203 raise ValidationError(ugettext(u'Select a valid choice. %s is not one of the available choices.') % val) 221 raise ValidationError(ugettext(u'Select a valid choice. %s is' 222 u' not one of the available' 223 u' choices.') % val) 204 224 else: 205 225 final_values.append(obj) django/branches/queryset-refactor/django/utils/cache.py
r6466 r6638 14 14 cache keys to prevent delivery of wrong content. 15 15 16 A example: i18n middleware would need to distinguish caches by the16 An example: i18n middleware would need to distinguish caches by the 17 17 "Accept-language" header. 18 18 """ … … 21 21 import re 22 22 import time 23 from email.Utils import formatdate 23 24 24 from django.conf import settings 25 25 from django.core.cache import cache 26 26 from django.utils.encoding import smart_str, iri_to_uri 27 from django.utils.http import http_date 27 28 28 29 cc_delim_re = re.compile(r'\s*,\s*') … … 41 42 """ 42 43 def dictitem(s): 43 t = s.split('=', 1)44 t = s.split('=', 1) 44 45 if len(t) > 1: 45 46 return (t[0].lower(), t[1]) … … 65 66 kwargs['max_age'] = min(cc['max-age'], kwargs['max_age']) 66 67 67 for (k, v) in kwargs.items():68 for (k, v) in kwargs.items(): 68 69 cc[k.replace('_', '-')] = v 69 70 cc = ', '.join([dictvalue(el) for el in cc.items()]) … … 89 90 response['ETag'] = md5.new(response.content).hexdigest() 90 91 if not response.has_header('Last-Modified'): 91 response['Last-Modified'] = formatdate()[:26] + "GMT"92 response['Last-Modified'] = http_date() 92 93 if not response.has_header('Expires'): 93 response['Expires'] = formatdate(time.time() + cache_timeout)[:26] + "GMT"94 response['Expires'] = http_date(time.time() + cache_timeout) 94 95 patch_cache_control(response, max_age=cache_timeout) 95 96 96 97 def add_never_cache_headers(response): 97 98 """ 98 Add headers to a response to indicate that 99 a page should never be cached. 99 Adds headers to a response to indicate that a page should never be cached. 100 100 """ 101 101 patch_response_headers(response, cache_timeout=-1) … … 120 120 121 121 def _generate_cache_key(request, headerlist, key_prefix): 122 " Returns a cache key from the headers given in the header list."122 """Returns a cache key from the headers given in the header list.""" 123 123 ctx = md5.new() 124 124 for header in headerlist: … … 126 126 if value is not None: 127 127 ctx.update(value) 128 return 'views.decorators.cache.cache_page.%s.%s.%s' % (key_prefix, iri_to_uri(request.path), ctx.hexdigest()) 128 return 'views.decorators.cache.cache_page.%s.%s.%s' % ( 129 key_prefix, iri_to_uri(request.path), ctx.hexdigest()) 129 130 130 131 def get_cache_key(request, key_prefix=None): … … 140 141 if key_prefix is None: 141 142 key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX 142 cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix, iri_to_uri(request.path)) 143 cache_key = 'views.decorators.cache.cache_header.%s.%s' % ( 144 key_prefix, iri_to_uri(request.path)) 143 145 headerlist = cache.get(cache_key, None) 144 146 if headerlist is not None: … … 164 166 if cache_timeout is None: 165 167 cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS 166 cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix, iri_to_uri(request.path)) 168 cache_key = 'views.decorators.cache.cache_header.%s.%s' % ( 169 key_prefix, iri_to_uri(request.path)) 167 170 if response.has_header('Vary'): 168 headerlist = ['HTTP_'+header.upper().replace('-', '_') for header in vary_delim_re.split(response['Vary'])] 171 headerlist = ['HTTP_'+header.upper().replace('-', '_') 172 for header in vary_delim_re.split(response['Vary'])] 169 173 cache.set(cache_key, headerlist, cache_timeout) 170 174 return _generate_cache_key(request, headerlist, key_prefix) django/branches/queryset-refactor/django/utils/http.py
r6597 r6638 1 1 import urllib 2 from email.Utils import formatdate 3 2 4 from django.utils.encoding import smart_str, force_unicode 3 5 from django.utils.functional import allow_lazy … … 38 40 doseq) 39 41 42 def cookie_date(epoch_seconds=None): 43 """ 44 Formats the time to ensure compatibility with Netscape's cookie standard. 45 46 Accepts a floating point number expressed in seconds since the epoch, in 47 UTC - such as that outputted by time.time(). If set to None, defaults to 48 the current time. 49 50 Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'. 51 """ 52 rfcdate = formatdate(epoch_seconds) 53 return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]) 54 55 def http_date(epoch_seconds=None): 56 """ 57 Formats the time to match the RFC1123 date format as specified by HTTP 58 RFC2616 section 3.3.1. 59 60 Accepts a floating point number expressed in seconds since the epoch, in 61 UTC - such as that outputted by time.time(). If set to None, defaults to 62 the current time. 63 64 Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. 65 """ 66 rfcdate = formatdate(epoch_seconds) 67 return '%s GMT' % rfcdate[:25] django/branches/queryset-refactor/django/views/static.py
r6597 r6638 8 8 import posixpath 9 9 import re 10 import rfc82211 10 import stat 12 11 import urllib 12 from email.Utils import parsedate_tz, mktime_tz 13 13 14 14 from django.template import loader 15 15 from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified 16 16 from django.template import Template, Context, TemplateDoesNotExist 17 from django.utils.http import http_date 17 18 18 19 def serve(request, path, document_root=None, show_indexes=False): … … 61 62 contents = open(fullpath, 'rb').read() 62 63 response = HttpResponse(contents, mimetype=mimetype) 63 response["Last-Modified"] = rfc822.formatdate(statobj[stat.ST_MTIME])64 response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) 64 65 return response 65 66 … … 120 121 matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, 121 122 re.IGNORECASE) 122 header_mtime = rfc822.mktime_tz(rfc822.parsedate_tz( 123 matches.group(1))) 123 header_mtime = mktime_tz(parsedate_tz(matches.group(1))) 124 124 header_len = matches.group(3) 125 125 if header_len and int(header_len) != size: django/branches/queryset-refactor/docs/cache.txt
r6597 r6638 292 292 ========================= 293 293 294 **New in development version**. 295 294 296 If you're after even more control, you can also cache template fragments using 295 the ``cache`` template tag. To give your template access to this tag, put ``{%296 load cache %}`` near the top of your template.297 the ``cache`` template tag. To give your template access to this tag, put 298 ``{% load cache %}`` near the top of your template. 297 299 298 300 The ``{% cache %}`` template tag caches the contents of the block for a given 299 amount of time. It takes at least two arguments: the cache timeout, in 300 seconds,and the name to give the cache fragment. For example::301 amount of time. It takes at least two arguments: the cache timeout, in seconds, 302 and the name to give the cache fragment. For example:: 301 303 302 304 {% load cache %} django/branches/queryset-refactor/docs/email.txt
r6466 r6638 276 276 277 277 * You can pass it a single argument that is an 278 ``email.MIM Base.MIMEBase`` instance. This will be inserted directly278 ``email.MIMEBase.MIMEBase`` instance. This will be inserted directly 279 279 into the resulting message. 280 280 django/branches/queryset-refactor/docs/form_preview.txt
r6339 r6638 46 46 2. Create a ``FormPreview`` subclass that overrides the ``done()`` method:: 47 47 48 from django.contrib.formtools import FormPreview48 from django.contrib.formtools.preview import FormPreview 49 49 from myapp.models import SomeModel 50 50 django/branches/queryset-refactor/docs/modpython.txt
r6597 r6638 151 151 <Location "/otherthing"> 152 152 SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings 153 PythonInterpreter mysite_other153 PythonInterpreter othersite 154 154 </Location> 155 155 </VirtualHost> django/branches/queryset-refactor/docs/testing.txt
r6340 r6638 722 722 723 723 from django.test import TestCase 724 from django.test.client import Client725 724 726 725 class SimpleTest(TestCase): django/branches/queryset-refactor/tests/regressiontests/text/tests.py
r6597 r6638 28 28 u'Paris+&+Orl%C3%A9ans' 29 29 30 ### cookie_date, http_date ############################################### 31 >>> from django.utils.http import cookie_date, http_date 32 >>> t = 1167616461.0 33 >>> cookie_date(t) 34 'Mon, 01-Jan-2007 01:54:21 GMT' 35 >>> http_date(t) 36 'Mon, 01 Jan 2007 01:54:21 GMT' 37 30 38 ### iri_to_uri ########################################################### 31 39 >>> from django.utils.encoding import iri_to_uri
