Django

Code

Changeset 6341

Show
Ignore:
Timestamp:
09/15/07 17:00:35 (1 year ago)
Author:
adrian
Message:

queryset-refactor: Merged to [6340]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/queryset-refactor/AUTHORS

    r6340 r6341  
    8888    flavio.curella@gmail.com 
    8989    Jure Cuhalev <gandalf@owca.info> 
     90    John D'Agostino <john.dagostino@gmail.com> 
    9091    dackze+django@gmail.com 
    9192    David Danier <goliath.mailinglist@gmx.de> 
  • django/branches/queryset-refactor/django/conf/global_settings.py

    r6340 r6341  
    272272############ 
    273273 
    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. 
     274SESSION_COOKIE_NAME = 'sessionid'                       # Cookie name. This can be whatever you want. 
     275SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2               # Age of cookie, in seconds (default: 2 weeks). 
     276SESSION_COOKIE_DOMAIN = None                            # A string like ".lawrence.com", or None for standard domain cookie. 
     277SESSION_COOKIE_SECURE = False                           # Whether the session cookie should be secure (https:// only). 
     278SESSION_SAVE_EVERY_REQUEST = False                      # Whether to save the session data on every request. 
     279SESSION_EXPIRE_AT_BROWSER_CLOSE = False                 # Whether sessions expire when a user closes his browser. 
     280SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # The module to store session data 
     281SESSION_FILE_PATH = '/tmp/'                             # Directory to store session files if using the file session module 
    280282 
    281283######### 
  • django/branches/queryset-refactor/django/contrib/auth/handlers/modpython.py

    r4265 r6341  
    1010    # that so that the following import works 
    1111    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() 
    1216 
    1317    # check for PythonOptions 
  • django/branches/queryset-refactor/django/contrib/auth/models.py

    r6340 r6341  
    1616    from sets import Set as set   # Python 2.3 fallback 
    1717 
    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': 
     18def 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': 
    3125        try: 
    3226            import crypt 
    3327        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 
     48def 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) 
    3755 
    3856class SiteProfileNotAvailable(Exception): 
     
    163181 
    164182    def set_password(self, raw_password): 
    165         import sha, random 
     183        import random 
    166184        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
    169187        self.password = '%s$%s$%s' % (algo, salt, hsh) 
    170188 
     
    177195        # algorithm or salt. 
    178196        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)) 
    181198            if is_correct: 
    182199                # Convert the password to the new, more secure format. 
  • django/branches/queryset-refactor/django/contrib/sessions/middleware.py

    r5712 r6341  
    11from django.conf import settings 
    2 from django.contrib.sessions.models import Session 
    3 from django.core.exceptions import SuspiciousOperation 
    42from django.utils.cache import patch_vary_headers 
    53from email.Utils import formatdate 
     
    108TEST_COOKIE_VALUE = 'worked' 
    119 
    12 class SessionWrapper(object): 
    13     def __init__(self, session_key): 
    14         self.session_key = session_key 
    15         self.accessed = False 
    16         self.modified = False 
     10class SessionMiddleware(object): 
    1711 
    18     def __contains__(self, key): 
    19         return key in self._session 
    20  
    21     def __getitem__(self, key): 
    22         return self._session[key] 
    23  
    24     def __setitem__(self, key, value): 
    25         self._session[key] = value 
    26         self.modified = True 
    27  
    28     def __delitem__(self, key): 
    29         del self._session[key] 
    30         self.modified = True 
    31  
    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._session 
    43         return self._session.pop(key, *args) 
    44  
    45     def set_test_cookie(self): 
    46         self[TEST_COOKIE_NAME] = TEST_COOKIE_VALUE 
    47  
    48     def test_cookie_worked(self): 
    49         return self.get(TEST_COOKIE_NAME) == TEST_COOKIE_VALUE 
    50  
    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 = True 
    57         try: 
    58             return self._session_cache 
    59         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 new 
    70                     # key, for extra security. 
    71                     self.session_key = None 
    72             return self._session_cache 
    73  
    74     _session = property(_get_session) 
    75  
    76 class SessionMiddleware(object): 
    7712    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)) 
    7915 
    8016    def process_response(self, request, response): 
     
    9026                patch_vary_headers(response, ('Cookie',)) 
    9127            if modified or settings.SESSION_SAVE_EVERY_REQUEST: 
    92                 if request.session.session_key: 
    93                     session_key = request.session.session_key 
    94                 else: 
    95                     obj = Session.objects.get_new_session_object() 
    96                     session_key = obj.session_key 
    97  
    9828                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: 
    9929                    max_age = None 
     
    10232                    max_age = settings.SESSION_COOKIE_AGE 
    10333                    rfcdate = formatdate(time.time() + settings.SESSION_COOKIE_AGE) 
     34                     
    10435                    # Fixed length date must have '-' separation in the format 
    10536                    # 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, 
    11143                    max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, 
    11244                    secure=settings.SESSION_COOKIE_SECURE or None) 
     45                     
    11346        return response 
  • django/branches/queryset-refactor/django/contrib/sessions/models.py

    r6340 r6341  
    1 import base64, md5, random, sys, datetime, os, time 
     1import base64, md5, random, sys, datetime 
    22import cPickle as pickle 
    33from django.db import models 
     
    7575    expire_date = models.DateTimeField(_('expire date')) 
    7676    objects = SessionManager() 
     77 
    7778    class Meta: 
    7879        db_table = 'django_session' 
  • django/branches/queryset-refactor/django/contrib/sessions/tests.py

    r5876 r6341  
    11r""" 
    2 >>> s = SessionWrapper(None) 
    32 
    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 
    76 
    8 >>> s.accessed 
     7>>> db_session = DatabaseSession() 
     8>>> db_session.modified 
    99False 
    10 >>> s.modified 
     10>>> db_session['cat'] = "dog" 
     11>>> db_session.modified 
     12True 
     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) 
     19True 
     20>>> db_session.delete(db_session.session_key) 
     21>>> db_session.exists(db_session.session_key) 
    1122False 
    1223 
    13 >>> s.pop('non existant key', 'does not exist') 
     24>>> file_session = FileSession() 
     25>>> file_session.modified 
     26False 
     27>>> file_session['cat'] = "dog" 
     28>>> file_session.modified 
     29True 
     30>>> file_session.pop('cat') 
     31'dog' 
     32>>> file_session.pop('some key', 'does not exist') 
    1433'does not exist' 
    15 >>> s.accessed 
     34>>> file_session.save() 
     35>>> file_session.exists(file_session.session_key) 
    1636True 
    17 >>> s.modified 
     37>>> file_session.delete(file_session.session_key) 
     38>>> file_session.exists(file_session.session_key) 
    1839False 
    1940 
    20 >>> s.pop('some key') 
    21 'exists' 
    22 >>> s.accessed 
     41>>> cache_session = CacheSession() 
     42>>> cache_session.modified 
     43False 
     44>>> cache_session['cat'] = "dog" 
     45>>> cache_session.modified 
    2346True 
    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') 
    2850'does not exist' 
     51>>> cache_session.save() 
     52>>> cache_session.delete(cache_session.session_key) 
     53>>> cache_session.exists(cache_session.session_key) 
     54False 
    2955""" 
    30  
    31 from django.contrib.sessions.middleware import SessionWrapper 
    3256 
    3357if __name__ == '__main__': 
  • django/branches/queryset-refactor/django/db/__init__.py

    r5076 r6341  
     1import os 
    12from django.conf import settings 
    23from django.core import signals 
     4from django.core.exceptions import ImproperlyConfigured 
    35from django.dispatch import dispatcher 
     6from django.utils.functional import curry 
    47 
    58__all__ = ('backend', 'connection', 'DatabaseError', 'IntegrityError') 
     
    912 
    1013try: 
    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), {}, {}, ['']) 
    1218except 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. 
    2535 
    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(
     36def _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), {}, {}, ['']
    2939 
     40# We don't want to import the introspect/creation modules unless  
     41# someone asks for 'em, so lazily load them on demmand. 
     42get_introspection_module = curry(_import_database_module, _import_path, 'introspection') 
     43get_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. 
     48runshell = lambda: _import_database_module(_import_path, "client").runshell() 
     49 
     50# Convenient aliases for backend bits. 
    3051connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS) 
    3152DatabaseError = backend.DatabaseError 
  • django/branches/queryset-refactor/django/test/client.py

    r6337 r6341  
    55from django.conf import settings 
    66from django.contrib.auth import authenticate, login 
    7 from django.contrib.sessions.models import Session 
    8 from django.contrib.sessions.middleware import SessionWrapper 
    97from django.core.handlers.base import BaseHandler 
    108from django.core.handlers.wsgi import WSGIRequest 
     
    133131        "Obtain the current session variables" 
    134132        if 'django.contrib.sessions' in settings.INSTALLED_APPS: 
     133            engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) 
    135134            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) 
    136135            if cookie: 
    137                 return SessionWrapper(cookie.value) 
     136                return engine.SessionStore(cookie.value) 
    138137        return {} 
    139138    session = property(_session) 
     
    248247        user = authenticate(**credentials) 
    249248        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, {}, {}, ['']
    251250 
    252251            # Create a fake request to store login details 
    253252            request = HttpRequest() 
    254             request.session = SessionWrapper(obj.session_key
     253            request.session = engine.SessionStore(
    255254            login(request, user) 
    256255 
    257256            # Set the cookie to represent the session 
    258             self.cookies[settings.SESSION_COOKIE_NAME] = obj.session_key 
     257            self.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key 
    259258            self.cookies[settings.SESSION_COOKIE_NAME]['max-age'] = None 
    260259            self.cookies[settings.SESSION_COOKIE_NAME]['path'] = '/' 
     
    263262            self.cookies[settings.SESSION_COOKIE_NAME]['expires'] = None 
    264263 
    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()    
    268266 
    269267            return True 
     
    276274        Causes the authenticated user to be logged out. 
    277275        """ 
    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) 
    283278        self.cookies = SimpleCookie() 
  • django/branches/queryset-refactor/django/views/i18n.py

    r6334 r6341  
    1717    any state. 
    1818    """ 
    19     next = request.GET.get('next', None) 
     19    next = request.REQUEST.get('next', None) 
    2020    if not next: 
    2121        next = request.META.get('HTTP_REFERER', None) 
  • django/branches/queryset-refactor/docs/apache_auth.txt

    r4420 r6341  
    2222 
    2323    <Location /example/> 
    24         AuthType basic 
     24        AuthType Basic 
    2525        AuthName "example.com" 
    2626        Require valid-user 
     
    2929        PythonAuthenHandler django.contrib.auth.handlers.modpython 
    3030    </Location> 
     31     
     32.. admonition:: Using the authentication handler with Apache 2.2 
    3133 
     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         
    3275By default, the authentication handler will limit access to the ``/example/`` 
    3376location to users marked as staff members.  You can use a set of 
  • django/branches/queryset-refactor/docs/cache.txt

    r6049 r6341  
    525525precedence, and the header values will be merged correctly.) 
    526526 
     527If you want to use headers to disable caching altogether,  
     528``django.views.decorators.never_cache`` is a view decorator that adds 
     529headers 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 
    527536.. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 
    528537 
  • django/branches/queryset-refactor/docs/db-api.txt

    r6340 r6341  
    952952If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary. 
    953953 
     954``iterator()`` 
     955~~~~~~~~~~~~ 
     956 
     957Evaluates the ``QuerySet`` (by performing the query) and returns an 
     958`iterator`_ over the results. A ``QuerySet`` typically reads all of 
     959its results and instantiates all of the corresponding objects the 
     960first time you access it; ``iterator()`` will instead read results and 
     961instantiate objects in discrete chunks, yielding them one at a 
     962time. For a ``QuerySet`` which returns a large number of objects, this 
     963often results in better performance and a significant reduction in 
     964memory use. 
     965 
     966Note that using ``iterator()`` on a ``QuerySet`` which has already 
     967been evaluated will force it to evaluate again, repeating the query. 
     968 
     969.. _iterator: http://www.python.org/dev/peps/pep-0234/ 
     970 
    954971``latest(field_name=None)`` 
    955972~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
  • django/branches/queryset-refactor/docs/model-api.txt

    r6337 r6341  
    179179 
    180180The admin represents this as an ``<input type="text">`` with a JavaScript 
    181 calendar and a shortcut for "Today." 
     181calendar, and a shortcut for "Today."  The JavaScript calendar will always start 
     182the week on a Sunday. 
    182183 
    183184``DateTimeField`` 
  • django/branches/queryset-refactor/docs/sessions.txt

    r5869 r6341  
    1111================= 
    1212 
    13 Sessions are implemented via a piece of middleware_ and a Django model
    14  
    15 To enable session functionality, do these two things
     13Sessions are implemented via a piece of middleware_
     14 
     15To enable session functionality, do the following
    1616 
    1717    * Edit the ``MIDDLEWARE_CLASSES`` setting and make sure 
     
    1919      The default ``settings.py`` created by ``django-admin.py startproject`` has 
    2020      ``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`_.  
    2528 
    2629If you don't want to use sessions, you might as well remove the 
     
    2932 
    3033.. _middleware: ../middleware/ 
     34 
     35Configuring the session engine 
     36============================== 
     37 
     38**New in development version**. 
     39 
     40By default, Django stores sessions in your database (using the model 
     41``django.contrib.sessions.models.Session``). Though this is convenient, in 
     42some setups it's faster to store session data elsewhere, so Django can be 
     43configured to store session data on your filesystem or in your cache. 
     44 
     45Using file-based sessions 
     46------------------------- 
     47 
     48To use file-based sessions, set the ``SESSION_ENGINE`` setting to 
     49``"django.contrib.sessions.backends.file"``. 
     50 
     51You might also want to set the ``SESSION_FILE_PATH`` setting (which 
     52defaults to ``/tmp``) to control where Django stores session files. Be 
     53sure to check that your web server has permissions to read and write to 
     54this location. 
     55 
     56Using cache-based sessions 
     57-------------------------- 
     58 
     59To store session data using Django's cache system, set ``SESSION_ENGINE`` 
     60to ``"django.contrib.sessions.backends.cache"``. You'll want to make sure 
     61you'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. 
    3172 
    3273Using sessions in views 
     
    154195=========================== 
    155196 
    156 Internally, each session is just a normal Django model. The ``Session`` model 
     197The ``SessionStore`` which implements the session storage method can be imported 
     198and 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 
     207Or if you are using the ``django.contrib.sessions.engine.db`` each  
     208session is just a normal Django model. The ``Session`` model 
    157209is defined in ``django/contrib/sessions/models.py``. Because it's a normal 
    158210model, you can access sessions using the normal Django database API:: 
     
    161213    >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') 
    162214    >>> s.expire_date 
    163     datetime.datetime(2005, 8, 20, 13, 35, 12) 
     215    datetime.datetime(2005, 8, 20, 13, 35, 12)   
    164216 
    165217Note that you'll need to call ``get_decoded()`` to get the session dictionary. 
     
    246298A few `Django settings`_ give you control over session behavior: 
    247299 
     300SESSION_ENGINE 
     301-------------- 
     302 
     303**New in Django development version** 
     304 
     305Default: ``django.contrib.sessions.backends.db`` 
     306 
     307Controls 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     
     313See `configuring the session engine`_ for more details. 
     314 
     315SESSION_FILE_PATH 
     316----------------- 
     317 
     318**New in Django development version** 
     319 
     320Default: ``/tmp/`` 
     321 
     322If you're using file-based session storage, this sets the directory in 
     323which Django will store session data. 
     324 
    248325SESSION_COOKIE_AGE 
    249326------------------ 
  • django/branches/queryset-refactor/docs/settings.txt

    r6335 r6341  
    254254Default: ``''`` (Empty string) 
    255255 
    256 The database backend to use. Either ``'postgresql_psycopg2'``, 
    257 ``'postgresql'``, ``'mysql'``,  ``'mysql_old'``, ``'sqlite3'``, 
    258 ``'oracle'``, or ``'ado_mssql'``. 
     256The database backend to use. The build-in database backends are 
     257``'postgresql_psycopg2'``, ``'postgresql'``, ``'mysql'``, ``'mysql_old'``, 
     258``'sqlite3'``, ``'oracle'``, or ``'ado_mssql'``. 
     259 
     260You can also use a database backend that doesn't ship with Django by 
     261setting ``DATABASE_ENGINE`` to a fully-qualified path (i.e. 
     262``mypackage.backends.whatever``). Writing a whole new database backend from 
     263scratch is left as an exercise to the reader. 
    259264 
    260265DATABASE_HOST 
     
    729734``ADMINS`` and ``MANAGERS``. 
    730735 
     736SESSION_ENGINE 
     737-------------- 
     738 
     739**New in Django development version** 
     740 
     741Default: ``django.contrib.sessions.backends.db`` 
     742 
     743Controls 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     
     749See the `session docs`_ for more details. 
     750 
    731751SESSION_COOKIE_AGE 
    732752------------------ 
     
    770790Whether to expire the session when the user closes his or her browser. 
    771791See the `session docs`_. 
     792 
     793SESSION_FILE_PATH 
     794----------------- 
     795 
     796**New in Django development version** 
     797 
     798Default: ``/tmp/`` 
     799 
     800If you're using file-based session storage, this sets the directory in 
     801which Django will store session data. See the `session docs`_ for 
     802more details. 
    772803 
    773804SESSION_SAVE_EVERY_REQUEST 
  • django/branches/queryset-refactor/docs/templates_python.txt

    r6334 r6341  
    556556setting. It uses each loader until a loader finds a match. 
    557557 
     558The ``render_to_string()`` shortcut 
     559=================================== 
     560 
     561To cut down on the repetitive nature of loading and rendering 
     562templates, Django provides a shortcut function which largely 
     563automates the process: ``render_to_string()`` in 
     564``django.template.loader``, which loads a template, renders it and 
     565returns the resulting string:: 
     566 
     567    from django.template.loader import render_to_string 
     568    rendered = render_to_string('my_template.html', { 'foo': 'bar' }) 
     569 
     570The ``render_to_string`` shortcut takes one required argument -- 
     571``template_name``, which should be the name of the template to load 
     572and 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 
     584See also the `render_to_response()`_ shortcut, which calls 
     585``render_to_string`` and feeds the result into an ``HttpResponse`` 
     586suitable for returning directly from a view. 
     587 
     588.. _render_to_response(): ../shortcuts/#render-to-response 
     589 
    558590Extending the template system 
    559591=============================