Changeset 6341
- Timestamp:
- 09/15/07 17:00:35 (1 year ago)
- Files:
-
- django/branches/queryset-refactor/AUTHORS (modified) (1 diff)
- django/branches/queryset-refactor/django/conf/global_settings.py (modified) (1 diff)
- django/branches/queryset-refactor/django/contrib/auth/handlers/modpython.py (modified) (1 diff)
- django/branches/queryset-refactor/django/contrib/auth/models.py (modified) (3 diffs)
- django/branches/queryset-refactor/django/contrib/sessions/backends (copied) (copied from django/trunk/django/contrib/sessions/backends)
- django/branches/queryset-refactor/django/contrib/sessions/backends/base.py (copied) (copied from django/trunk/django/contrib/sessions/backends/base.py)
- django/branches/queryset-refactor/django/contrib/sessions/backends/cache.py (copied) (copied from django/trunk/django/contrib/sessions/backends/cache.py)
- django/branches/queryset-refactor/django/contrib/sessions/backends/db.py (copied) (copied from django/trunk/django/contrib/sessions/backends/db.py)
- django/branches/queryset-refactor/django/contrib/sessions/backends/file.py (copied) (copied from django/trunk/django/contrib/sessions/backends/file.py)
- django/branches/queryset-refactor/django/contrib/sessions/backends/__init__.py (copied) (copied from django/trunk/django/contrib/sessions/backends/__init__.py)
- django/branches/queryset-refactor/django/contrib/sessions/middleware.py (modified) (4 diffs)
- django/branches/queryset-refactor/django/contrib/sessions/models.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/contrib/sessions/tests.py (modified) (1 diff)
- django/branches/queryset-refactor/django/db/__init__.py (modified) (2 diffs)
- django/branches/queryset-refactor/django/test/client.py (modified) (5 diffs)
- django/branches/queryset-refactor/django/views/i18n.py (modified) (1 diff)
- django/branches/queryset-refactor/docs/apache_auth.txt (modified) (2 diffs)
- django/branches/queryset-refactor/docs/cache.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/contenttypes.txt (copied) (copied from django/trunk/docs/contenttypes.txt)
- django/branches/queryset-refactor/docs/db-api.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/model-api.txt (modified) (1 diff)
- django/branches/queryset-refactor/docs/sessions.txt (modified) (6 diffs)
- django/branches/queryset-refactor/docs/settings.txt (modified) (3 diffs)
- django/branches/queryset-refactor/docs/templates_python.txt (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/queryset-refactor/AUTHORS
r6340 r6341 88 88 flavio.curella@gmail.com 89 89 Jure Cuhalev <gandalf@owca.info> 90 John D'Agostino <john.dagostino@gmail.com> 90 91 dackze+django@gmail.com 91 92 David Danier <goliath.mailinglist@gmx.de> django/branches/queryset-refactor/django/conf/global_settings.py
r6340 r6341 272 272 ############ 273 273 274 SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. 275 SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). 276 SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. 277 SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). 278 SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. 279 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether sessions expire when a user closes his browser. 274 SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. 275 SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). 276 SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. 277 SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). 278 SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. 279 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether sessions expire when a user closes his browser. 280 SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data 281 SESSION_FILE_PATH = '/tmp/' # Directory to store session files if using the file session module 280 282 281 283 ######### django/branches/queryset-refactor/django/contrib/auth/handlers/modpython.py
r4265 r6341 10 10 # that so that the following import works 11 11 os.environ.update(req.subprocess_env) 12 13 # apache 2.2 requires a call to req.get_basic_auth_pw() before 14 # req.user and friends are available. 15 req.get_basic_auth_pw() 12 16 13 17 # check for PythonOptions django/branches/queryset-refactor/django/contrib/auth/models.py
r6340 r6341 16 16 from sets import Set as set # Python 2.3 fallback 17 17 18 def check_password(raw_password, enc_password): 19 """ 20 Returns a boolean of whether the raw_password was correct. Handles 21 encryption formats behind the scenes. 22 """ 23 algo, salt, hsh = enc_password.split('$') 24 if algo == 'md5': 25 import md5 26 return hsh == md5.new(smart_str(salt + raw_password)).hexdigest() 27 elif algo == 'sha1': 28 import sha 29 return hsh == sha.new(smart_str(salt + raw_password)).hexdigest() 30 elif algo == 'crypt': 18 def get_hexdigest(algorithm, salt, raw_password): 19 """ 20 Returns a string of the hexdigest of the given plaintext password and salt 21 using the given algorithm ('md5', 'sha1' or 'crypt'). 22 """ 23 raw_password, salt = smart_str(raw_password), smart_str(salt) 24 if algorithm == 'crypt': 31 25 try: 32 26 import crypt 33 27 except ImportError: 34 raise ValueError, "Crypt password algorithm not supported in this environment." 35 return hsh == crypt.crypt(smart_str(raw_password), smart_str(salt)) 36 raise ValueError, "Got unknown password algorithm type in password." 28 raise ValueError('"crypt" password algorithm not supported in this environment') 29 return crypt.crypt(raw_password, salt) 30 # The rest of the supported algorithms are supported by hashlib, but 31 # hashlib is only available in Python 2.5. 32 try: 33 import hashlib 34 except ImportError: 35 if algorithm == 'md5': 36 import md5 37 return md5.new(salt + raw_password).hexdigest() 38 elif algorithm == 'sha1': 39 import sha 40 return sha.new(salt + raw_password).hexdigest() 41 else: 42 if algorithm == 'md5': 43 return hashlib.md5(salt + raw_password).hexdigest() 44 elif algorithm == 'sha1': 45 return hashlib.sha1(salt + raw_password).hexdigest() 46 raise ValueError("Got unknown password algorithm type in password.") 47 48 def check_password(raw_password, enc_password): 49 """ 50 Returns a boolean of whether the raw_password was correct. Handles 51 encryption formats behind the scenes. 52 """ 53 algo, salt, hsh = enc_password.split('$') 54 return hsh == get_hexdigest(algo, salt, raw_password) 37 55 38 56 class SiteProfileNotAvailable(Exception): … … 163 181 164 182 def set_password(self, raw_password): 165 import sha,random183 import random 166 184 algo = 'sha1' 167 salt = sha.new(str(random.random())).hexdigest()[:5]168 hsh = sha.new(salt + smart_str(raw_password)).hexdigest()185 salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] 186 hsh = get_hexdigest(algo, salt, raw_password) 169 187 self.password = '%s$%s$%s' % (algo, salt, hsh) 170 188 … … 177 195 # algorithm or salt. 178 196 if '$' not in self.password: 179 import md5 180 is_correct = (self.password == md5.new(smart_str(raw_password)).hexdigest()) 197 is_correct = (self.password == get_hexdigest('md5', '', raw_password)) 181 198 if is_correct: 182 199 # Convert the password to the new, more secure format. django/branches/queryset-refactor/django/contrib/sessions/middleware.py
r5712 r6341 1 1 from django.conf import settings 2 from django.contrib.sessions.models import Session3 from django.core.exceptions import SuspiciousOperation4 2 from django.utils.cache import patch_vary_headers 5 3 from email.Utils import formatdate … … 10 8 TEST_COOKIE_VALUE = 'worked' 11 9 12 class SessionWrapper(object): 13 def __init__(self, session_key): 14 self.session_key = session_key 15 self.accessed = False 16 self.modified = False 10 class SessionMiddleware(object): 17 11 18 def __contains__(self, key):19 return key in self._session20 21 def __getitem__(self, key):22 return self._session[key]23 24 def __setitem__(self, key, value):25 self._session[key] = value26 self.modified = True27 28 def __delitem__(self, key):29 del self._session[key]30 self.modified = True31 32 def keys(self):33 return self._session.keys()34 35 def items(self):36 return self._session.items()37 38 def get(self, key, default=None):39 return self._session.get(key, default)40 41 def pop(self, key, *args):42 self.modified = self.modified or key in self._session43 return self._session.pop(key, *args)44 45 def set_test_cookie(self):46 self[TEST_COOKIE_NAME] = TEST_COOKIE_VALUE47 48 def test_cookie_worked(self):49 return self.get(TEST_COOKIE_NAME) == TEST_COOKIE_VALUE50 51 def delete_test_cookie(self):52 del self[TEST_COOKIE_NAME]53 54 def _get_session(self):55 # Lazily loads session from storage.56 self.accessed = True57 try:58 return self._session_cache59 except AttributeError:60 if self.session_key is None:61 self._session_cache = {}62 else:63 try:64 s = Session.objects.get(session_key=self.session_key,65 expire_date__gt=datetime.datetime.now())66 self._session_cache = s.get_decoded()67 except (Session.DoesNotExist, SuspiciousOperation):68 self._session_cache = {}69 # Set the session_key to None to force creation of a new70 # key, for extra security.71 self.session_key = None72 return self._session_cache73 74 _session = property(_get_session)75 76 class SessionMiddleware(object):77 12 def process_request(self, request): 78 request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) 13 engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 14 request.session = engine.SessionStore(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) 79 15 80 16 def process_response(self, request, response): … … 90 26 patch_vary_headers(response, ('Cookie',)) 91 27 if modified or settings.SESSION_SAVE_EVERY_REQUEST: 92 if request.session.session_key:93 session_key = request.session.session_key94 else:95 obj = Session.objects.get_new_session_object()96 session_key = obj.session_key97 98 28 if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: 99 29 max_age = None … … 102 32 max_age = settings.SESSION_COOKIE_AGE 103 33 rfcdate = formatdate(time.time() + settings.SESSION_COOKIE_AGE) 34 104 35 # Fixed length date must have '-' separation in the format 105 36 # DD-MMM-YYYY for compliance with Netscape cookie standard 106 expires = (rfcdate[:7] + "-" + rfcdate[8:11] 107 + "-" + rfcdate[12:26] + "GMT") 108 new_session = Session.objects.save(session_key, request.session._session, 109 datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)) 110 response.set_cookie(settings.SESSION_COOKIE_NAME, session_key, 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 40 # Save the seesion data and refresh the client cookie. 41 request.session.save() 42 response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, 111 43 max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, 112 44 secure=settings.SESSION_COOKIE_SECURE or None) 45 113 46 return response django/branches/queryset-refactor/django/contrib/sessions/models.py
r6340 r6341 1 import base64, md5, random, sys, datetime , os, time1 import base64, md5, random, sys, datetime 2 2 import cPickle as pickle 3 3 from django.db import models … … 75 75 expire_date = models.DateTimeField(_('expire date')) 76 76 objects = SessionManager() 77 77 78 class Meta: 78 79 db_table = 'django_session' django/branches/queryset-refactor/django/contrib/sessions/tests.py
r5876 r6341 1 1 r""" 2 >>> s = SessionWrapper(None)3 2 4 Inject data into the session cache. 5 >>> s._session_cache = {}6 >>> s._session_cache['some key'] = 'exists'3 >>> from django.contrib.sessions.backends.db import SessionStore as DatabaseSession 4 >>> from django.contrib.sessions.backends.cache import SessionStore as CacheSession 5 >>> from django.contrib.sessions.backends.file import SessionStore as FileSession 7 6 8 >>> s.accessed 7 >>> db_session = DatabaseSession() 8 >>> db_session.modified 9 9 False 10 >>> s.modified 10 >>> db_session['cat'] = "dog" 11 >>> db_session.modified 12 True 13 >>> db_session.pop('cat') 14 'dog' 15 >>> db_session.pop('some key', 'does not exist') 16 'does not exist' 17 >>> db_session.save() 18 >>> db_session.exists(db_session.session_key) 19 True 20 >>> db_session.delete(db_session.session_key) 21 >>> db_session.exists(db_session.session_key) 11 22 False 12 23 13 >>> s.pop('non existant key', 'does not exist') 24 >>> file_session = FileSession() 25 >>> file_session.modified 26 False 27 >>> file_session['cat'] = "dog" 28 >>> file_session.modified 29 True 30 >>> file_session.pop('cat') 31 'dog' 32 >>> file_session.pop('some key', 'does not exist') 14 33 'does not exist' 15 >>> s.accessed 34 >>> file_session.save() 35 >>> file_session.exists(file_session.session_key) 16 36 True 17 >>> s.modified 37 >>> file_session.delete(file_session.session_key) 38 >>> file_session.exists(file_session.session_key) 18 39 False 19 40 20 >>> s.pop('some key') 21 'exists' 22 >>> s.accessed 41 >>> cache_session = CacheSession() 42 >>> cache_session.modified 43 False 44 >>> cache_session['cat'] = "dog" 45 >>> cache_session.modified 23 46 True 24 >>> s.modified 25 True 26 27 >>> s.pop('some key', 'does not exist') 47 >>> cache_session.pop('cat') 48 'dog' 49 >>> cache_session.pop('some key', 'does not exist') 28 50 'does not exist' 51 >>> cache_session.save() 52 >>> cache_session.delete(cache_session.session_key) 53 >>> cache_session.exists(cache_session.session_key) 54 False 29 55 """ 30 31 from django.contrib.sessions.middleware import SessionWrapper32 56 33 57 if __name__ == '__main__': django/branches/queryset-refactor/django/db/__init__.py
r5076 r6341 1 import os 1 2 from django.conf import settings 2 3 from django.core import signals 4 from django.core.exceptions import ImproperlyConfigured 3 5 from django.dispatch import dispatcher 6 from django.utils.functional import curry 4 7 5 8 __all__ = ('backend', 'connection', 'DatabaseError', 'IntegrityError') … … 9 12 10 13 try: 11 backend = __import__('django.db.backends.%s.base' % settings.DATABASE_ENGINE, {}, {}, ['']) 14 # Most of the time, the database backend will be one of the official 15 # backends that ships with Django, so look there first. 16 _import_path = 'django.db.backends.' 17 backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, ['']) 12 18 except ImportError, e: 13 # The database backend wasn't found. Display a helpful error message 14 # listing all possible database backends. 15 from django.core.exceptions import ImproperlyConfigured 16 import os 17 backend_dir = os.path.join(__path__[0], 'backends') 18 available_backends = [f for f in os.listdir(backend_dir) if not f.startswith('_') and not f.startswith('.') and not f.endswith('.py') and not f.endswith('.pyc')] 19 available_backends.sort() 20 if settings.DATABASE_ENGINE not in available_backends: 21 raise ImproperlyConfigured, "%r isn't an available database backend. Available options are: %s" % \ 22 (settings.DATABASE_ENGINE, ", ".join(map(repr, available_backends))) 23 else: 24 raise # If there's some other error, this must be an error in Django itself. 19 # If the import failed, we might be looking for a database backend 20 # distributed external to Django. So we'll try that next. 21 try: 22 _import_path = '' 23 backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, ['']) 24 except ImportError, e_user: 25 # The database backend wasn't found. Display a helpful error message 26 # listing all possible (built-in) database backends. 27 backend_dir = os.path.join(__path__[0], 'backends') 28 available_backends = [f for f in os.listdir(backend_dir) if not f.startswith('_') and not f.startswith('.') and not f.endswith('.py') and not f.endswith('.pyc')] 29 available_backends.sort() 30 if settings.DATABASE_ENGINE not in available_backends: 31 raise ImproperlyConfigured, "%r isn't an available database backend. Available options are: %s" % \ 32 (settings.DATABASE_ENGINE, ", ".join(map(repr, available_backends))) 33 else: 34 raise # If there's some other error, this must be an error in Django itself. 25 35 26 get_introspection_module = lambda: __import__('django.db.backends.%s.introspection' % settings.DATABASE_ENGINE, {}, {}, ['']) 27 get_creation_module = lambda: __import__('django.db.backends.%s.creation' % settings.DATABASE_ENGINE, {}, {}, ['']) 28 runshell = lambda: __import__('django.db.backends.%s.client' % settings.DATABASE_ENGINE, {}, {}, ['']).runshell()36 def _import_database_module(import_path='', module_name=''): 37 """Lazyily import a database module when requested.""" 38 return __import__('%s%s.%s' % (_import_path, settings.DATABASE_ENGINE, module_name), {}, {}, ['']) 29 39 40 # We don't want to import the introspect/creation modules unless 41 # someone asks for 'em, so lazily load them on demmand. 42 get_introspection_module = curry(_import_database_module, _import_path, 'introspection') 43 get_creation_module = curry(_import_database_module, _import_path, 'creation') 44 45 # We want runshell() to work the same way, but we have to treat it a 46 # little differently (since it just runs instead of returning a module like 47 # the above) and wrap the lazily-loaded runshell() method. 48 runshell = lambda: _import_database_module(_import_path, "client").runshell() 49 50 # Convenient aliases for backend bits. 30 51 connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS) 31 52 DatabaseError = backend.DatabaseError django/branches/queryset-refactor/django/test/client.py
r6337 r6341 5 5 from django.conf import settings 6 6 from django.contrib.auth import authenticate, login 7 from django.contrib.sessions.models import Session8 from django.contrib.sessions.middleware import SessionWrapper9 7 from django.core.handlers.base import BaseHandler 10 8 from django.core.handlers.wsgi import WSGIRequest … … 133 131 "Obtain the current session variables" 134 132 if 'django.contrib.sessions' in settings.INSTALLED_APPS: 133 engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 135 134 cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) 136 135 if cookie: 137 return SessionWrapper(cookie.value)136 return engine.SessionStore(cookie.value) 138 137 return {} 139 138 session = property(_session) … … 248 247 user = authenticate(**credentials) 249 248 if user and user.is_active and 'django.contrib.sessions' in settings.INSTALLED_APPS: 250 obj = Session.objects.get_new_session_object()249 engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 251 250 252 251 # Create a fake request to store login details 253 252 request = HttpRequest() 254 request.session = SessionWrapper(obj.session_key)253 request.session = engine.SessionStore() 255 254 login(request, user) 256 255 257 256 # Set the cookie to represent the session 258 self.cookies[settings.SESSION_COOKIE_NAME] = obj.session_key257 self.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key 259 258 self.cookies[settings.SESSION_COOKIE_NAME]['max-age'] = None 260 259 self.cookies[settings.SESSION_COOKIE_NAME]['path'] = '/' … … 263 262 self.cookies[settings.SESSION_COOKIE_NAME]['expires'] = None 264 263 265 # Set the session values 266 Session.objects.save(obj.session_key, request.session._session, 267 datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)) 264 # Save the session values 265 request.session.save() 268 266 269 267 return True … … 276 274 Causes the authenticated user to be logged out. 277 275 """ 278 try: 279 Session.objects.get(session_key=self.cookies['sessionid'].value).delete() 280 except KeyError: 281 pass 282 276 session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore() 277 session.delete(session_key=self.cookies['sessionid'].value) 283 278 self.cookies = SimpleCookie() django/branches/queryset-refactor/django/views/i18n.py
r6334 r6341 17 17 any state. 18 18 """ 19 next = request. GET.get('next', None)19 next = request.REQUEST.get('next', None) 20 20 if not next: 21 21 next = request.META.get('HTTP_REFERER', None) django/branches/queryset-refactor/docs/apache_auth.txt
r4420 r6341 22 22 23 23 <Location /example/> 24 AuthType basic24 AuthType Basic 25 25 AuthName "example.com" 26 26 Require valid-user … … 29 29 PythonAuthenHandler django.contrib.auth.handlers.modpython 30 30 </Location> 31 32 .. admonition:: Using the authentication handler with Apache 2.2 31 33 34 If you're using Apache 2.2, you'll need to take a couple extra steps. 35 36 You'll need to ensure that ``mod_auth_basic`` and ``mod_authz_user`` 37 are loaded. These might be compiled staticly into Apache, or you might 38 need to use ``LoadModule`` to load them dynamically (as shown in the 39 example at the bottom of this note). 40 41 You'll also need to insert configuration directives that prevent Apache 42 from trying to use other authentication modules. Depnding on which other 43 authentication modules you have loaded, you might need one or more of 44 the following directives:: 45 46 AuthBasicAuthoritative Off 47 AuthDefaultAuthoritative Off 48 AuthzLDAPAuthoritative Off 49 AuthzDBMAuthoritative Off 50 AuthzDefaultAuthoritative Off 51 AuthzGroupFileAuthoritative Off 52 AuthzOwnerAuthoritative Off 53 AuthzUserAuthoritative Off 54 55 A complete configuration, with differences between Apache 2.0 and 56 Apache 2.2 marked in bold, would look something like: 57 58 .. parsed-literal:: 59 60 **LoadModule auth_basic_module modules/mod_auth_basic.so** 61 **LoadModule authz_user_module modules/mod_authz_user.so** 62 63 ... 64 65 <Location /exmaple/> 66 AuthType Basic 67 AuthName "example.com" 68 **AuthBasicAuthoritative Off** 69 Require valid-user 70 71 SetEnv DJANGO_SETTINGS_MODULE mysite.settings 72 PythonAuthenHandler django.contrib.auth.handlers.modpython 73 </Location> 74 32 75 By default, the authentication handler will limit access to the ``/example/`` 33 76 location to users marked as staff members. You can use a set of django/branches/queryset-refactor/docs/cache.txt
r6049 r6341 525 525 precedence, and the header values will be merged correctly.) 526 526 527 If you want to use headers to disable caching altogether, 528 ``django.views.decorators.never_cache`` is a view decorator that adds 529 headers to ensure the response won't be cached by browsers or other caches. Example:: 530 531 from django.views.decorators.cache import never_cache 532 @never_cache 533 def myview(request): 534 ... 535 527 536 .. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 528 537 django/branches/queryset-refactor/docs/db-api.txt
r6340 r6341 952 952 If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary. 953 953 954 ``iterator()`` 955 ~~~~~~~~~~~~ 956 957 Evaluates the ``QuerySet`` (by performing the query) and returns an 958 `iterator`_ over the results. A ``QuerySet`` typically reads all of 959 its results and instantiates all of the corresponding objects the 960 first time you access it; ``iterator()`` will instead read results and 961 instantiate objects in discrete chunks, yielding them one at a 962 time. For a ``QuerySet`` which returns a large number of objects, this 963 often results in better performance and a significant reduction in 964 memory use. 965 966 Note that using ``iterator()`` on a ``QuerySet`` which has already 967 been evaluated will force it to evaluate again, repeating the query. 968 969 .. _iterator: http://www.python.org/dev/peps/pep-0234/ 970 954 971 ``latest(field_name=None)`` 955 972 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ django/branches/queryset-refactor/docs/model-api.txt
r6337 r6341 179 179 180 180 The admin represents this as an ``<input type="text">`` with a JavaScript 181 calendar and a shortcut for "Today." 181 calendar, and a shortcut for "Today." The JavaScript calendar will always start 182 the week on a Sunday. 182 183 183 184 ``DateTimeField`` django/branches/queryset-refactor/docs/sessions.txt
r5869 r6341 11 11 ================= 12 12 13 Sessions are implemented via a piece of middleware_ and a Django model.14 15 To enable session functionality, do the se two things:13 Sessions are implemented via a piece of middleware_. 14 15 To enable session functionality, do the following: 16 16 17 17 * Edit the ``MIDDLEWARE_CLASSES`` setting and make sure … … 19 19 The default ``settings.py`` created by ``django-admin.py startproject`` has 20 20 ``SessionMiddleware`` activated. 21 22 * Add ``'django.contrib.sessions'`` to your ``INSTALLED_APPS`` setting, and 23 run ``manage.py syncdb`` to install the single database table that stores 24 session data. 21 22 * Add ``'django.contrib.sessions'`` to your ``INSTALLED_APPS`` setting, 23 and run ``manage.py syncdb`` to install the single database table 24 that stores session data. 25 26 **New in development version**: this step is optional if you're not using 27 the database session backend; see `configuring the session engine`_. 25 28 26 29 If you don't want to use sessions, you might as well remove the … … 29 32 30 33 .. _middleware: ../middleware/ 34 35 Configuring the session engine 36 ============================== 37 38 **New in development version**. 39 40 By default, Django stores sessions in your database (using the model 41 ``django.contrib.sessions.models.Session``). Though this is convenient, in 42 some setups it's faster to store session data elsewhere, so Django can be 43 configured to store session data on your filesystem or in your cache. 44 45 Using file-based sessions 46 ------------------------- 47 48 To use file-based sessions, set the ``SESSION_ENGINE`` setting to 49 ``"django.contrib.sessions.backends.file"``. 50 51 You might also want to set the ``SESSION_FILE_PATH`` setting (which 52 defaults to ``/tmp``) to control where Django stores session files. Be 53 sure to check that your web server has permissions to read and write to 54 this location. 55 56 Using cache-based sessions 57 -------------------------- 58 59 To store session data using Django's cache system, set ``SESSION_ENGINE`` 60 to ``"django.contrib.sessions.backends.cache"``. You'll want to make sure 61 you've configured your cache; see the `cache documentation`_ for details. 62 63 .. _cache documentation: ../cache/ 64 65 .. note:: 66 67 You probably don't want to use cache-based sessions if you're not using 68 the memcached cache backend. The local memory and simple cache backends 69 don't retain data long enough to be good choices, and it'll be faster 70 to use file or database sessions directly instead of sending everything 71 through the file or database cache backends. 31 72 32 73 Using sessions in views … … 154 195 =========================== 155 196 156 Internally, each session is just a normal Django model. The ``Session`` model 197 The ``SessionStore`` which implements the session storage method can be imported 198 and a API is available to manipulate the session data outside of a view:: 199 200 >>> from django.contrib.sessions.engines.db import SessionStore 201 >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead') 202 >>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10) 203 >>> s['last_login'] 204 datetime.datetime(2005, 8, 20, 13, 35, 0) 205 >>> s.save() 206 207 Or if you are using the ``django.contrib.sessions.engine.db`` each 208 session is just a normal Django model. The ``Session`` model 157 209 is defined in ``django/contrib/sessions/models.py``. Because it's a normal 158 210 model, you can access sessions using the normal Django database API:: … … 161 213 >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') 162 214 >>> s.expire_date 163 datetime.datetime(2005, 8, 20, 13, 35, 12) 215 datetime.datetime(2005, 8, 20, 13, 35, 12) 164 216 165 217 Note that you'll need to call ``get_decoded()`` to get the session dictionary. … … 246 298 A few `Django settings`_ give you control over session behavior: 247 299 300 SESSION_ENGINE 301 -------------- 302 303 **New in Django development version** 304 305 Default: ``django.contrib.sessions.backends.db`` 306 307 Controls where Django stores session data. Valid values are: 308 309 * ``'django.contrib.sessions.backends.db'`` 310 * ``'django.contrib.sessions.backends.file'`` 311 * ``'django.contrib.sessions.backends.cache'`` 312 313 See `configuring the session engine`_ for more details. 314 315 SESSION_FILE_PATH 316 ----------------- 317 318 **New in Django development version** 319 320 Default: ``/tmp/`` 321 322 If you're using file-based session storage, this sets the directory in 323 which Django will store session data. 324 248 325 SESSION_COOKIE_AGE 249 326 ------------------ django/branches/queryset-refactor/docs/settings.txt
r6335 r6341 254 254 Default: ``''`` (Empty string) 255 255 256 The database backend to use. Either ``'postgresql_psycopg2'``, 257 ``'postgresql'``, ``'mysql'``, ``'mysql_old'``, ``'sqlite3'``, 258 ``'oracle'``, or ``'ado_mssql'``. 256 The database backend to use. The build-in database backends are 257 ``'postgresql_psycopg2'``, ``'postgresql'``, ``'mysql'``, ``'mysql_old'``, 258 ``'sqlite3'``, ``'oracle'``, or ``'ado_mssql'``. 259 260 You can also use a database backend that doesn't ship with Django by 261 setting ``DATABASE_ENGINE`` to a fully-qualified path (i.e. 262 ``mypackage.backends.whatever``). Writing a whole new database backend from 263 scratch is left as an exercise to the reader. 259 264 260 265 DATABASE_HOST … … 729 734 ``ADMINS`` and ``MANAGERS``. 730 735 736 SESSION_ENGINE 737 -------------- 738 739 **New in Django development version** 740 741 Default: ``django.contrib.sessions.backends.db`` 742 743 Controls where Django stores session data. Valid values are: 744 745 * ``'django.contrib.sessions.backends.db'`` 746 * ``'django.contrib.sessions.backends.file'`` 747 * ``'django.contrib.sessions.backends.cache'`` 748 749 See the `session docs`_ for more details. 750 731 751 SESSION_COOKIE_AGE 732 752 ------------------ … … 770 790 Whether to expire the session when the user closes his or her browser. 771 791 See the `session docs`_. 792 793 SESSION_FILE_PATH 794 ----------------- 795 796 **New in Django development version** 797 798 Default: ``/tmp/`` 799 800 If you're using file-based session storage, this sets the directory in 801 which Django will store session data. See the `session docs`_ for 802 more details. 772 803 773 804 SESSION_SAVE_EVERY_REQUEST django/branches/queryset-refactor/docs/templates_python.txt
r6334 r6341 556 556 setting. It uses each loader until a loader finds a match. 557 557 558 The ``render_to_string()`` shortcut 559 =================================== 560 561 To cut down on the repetitive nature of loading and rendering 562 templates, Django provides a shortcut function which largely 563 automates the process: ``render_to_string()`` in 564 ``django.template.loader``, which loads a template, renders it and 565 returns the resulting string:: 566 567 from django.template.loader import render_to_string 568 rendered = render_to_string('my_template.html', { 'foo': 'bar' }) 569 570 The ``render_to_string`` shortcut takes one required argument -- 571 ``template_name``, which should be the name of the template to load 572 and render -- and two optional arguments:: 573 574 dictionary 575 A dictionary to be used as variables and values for the 576 template's context. This can also be passed as the second 577 positional argument. 578 579 context_instance 580 An instance of ``Context`` or a subclass (e.g., an instance of 581 ``RequestContext``) to use as the template's context. This can 582 also be passed as the third positional argument. 583 584 See also the `render_to_response()`_ shortcut, which calls 585 ``render_to_string`` and feeds the result into an ``HttpResponse`` 586 suitable for returning directly from a view. 587 588 .. _render_to_response(): ../shortcuts/#render-to-response 589 558 590 Extending the template system 559 591 =============================
