Ticket #925: request_processors_patch.diff

File request_processors_patch.diff, 15.6 KB (added by L.Plant.98@…, 19 years ago)

patch

  • django/conf/global_settings.py

     
    174174# http://www.djangoproject.com/documentation/templates/#now
    175175TIME_FORMAT = 'P'
    176176
     177# List of processors used by DjangoContext to populate the context. 
     178# Each one should be a callable that takes the request object as it's
     179# only parameter and returns a dictionary to add to the context.
     180REQUEST_PROCESSORS = (
     181    "django.core.processors.auth",
     182    "django.core.processors.debug",
     183    "django.core.processors.i18n",
     184)
     185
    177186##############
    178187# MIDDLEWARE #
    179188##############
  • django/core/extensions.py

     
    22# of MVC. In other words, these functions/classes introduce controlled coupling
    33# for convenience's sake.
    44
    5 from django.core.exceptions import Http404, ObjectDoesNotExist
     5from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured
    66from django.core.template import Context, loader
    7 from django.conf.settings import DEBUG, INTERNAL_IPS
     7from django.conf.settings import REQUEST_PROCESSORS
    88from django.utils.httpwrappers import HttpResponse
    99
     10# Load standard request processors
     11_standard_request_processors = []
     12
     13for path in REQUEST_PROCESSORS:
     14    i = path.rfind('.')
     15    module, attr = path[:i], path[i+1:]
     16    try:
     17        mod = __import__(module, globals(), locals(), [attr])
     18    except ImportError, e:
     19        raise ImproperlyConfigured, 'Error importing request processor module %s: "%s"' % (module, e)
     20    try:
     21        func = getattr(mod, attr)
     22    except AttributeError:
     23        raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable request processor' % (module, attr)
     24    _standard_request_processors.append(func)
     25
    1026def render_to_response(*args, **kwargs):
    1127    return HttpResponse(loader.render_to_string(*args, **kwargs))
    1228load_and_render = render_to_response # For backwards compatibility.
     
    2541
    2642class DjangoContext(Context):
    2743    """
    28     This subclass of template.Context automatically populates 'user' and
    29     'messages' in the context.
     44    This subclass of template.Context automatically populates itself using
     45    the request processors defined in REQUEST_PROCESSORS.
     46    Additional processors can be specified as a list of callables
     47    using keyword argument 'processors'.
    3048    """
    31     def __init__(self, request, dict=None):
     49    def __init__(self, request, dict=None, processors=None):
    3250        Context.__init__(self, dict)
    33         self['user'] = request.user
    34         self['messages'] = request.user.get_and_delete_messages()
    35         self['perms'] = PermWrapper(request.user)
    36         from django.conf import settings
    37         self['LANGUAGES'] = settings.LANGUAGES
    38         if hasattr(request, 'LANGUAGE_CODE'):
    39             self['LANGUAGE_CODE'] = request.LANGUAGE_CODE
     51        if processors is None:
     52            processors = []
    4053        else:
    41             self['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
    42         if DEBUG and request.META.get('REMOTE_ADDR') in INTERNAL_IPS:
    43             self['debug'] = True
    44             from django.core import db
    45             self['sql_queries'] = db.db.queries
    46 
    47 # PermWrapper and PermLookupDict proxy the permissions system into objects that
    48 # the template system can understand.
    49 
    50 class PermLookupDict:
    51     def __init__(self, user, module_name):
    52         self.user, self.module_name = user, module_name
    53     def __repr__(self):
    54         return str(self.user.get_permission_list())
    55     def __getitem__(self, perm_name):
    56         return self.user.has_perm("%s.%s" % (self.module_name, perm_name))
    57     def __nonzero__(self):
    58         return self.user.has_module_perms(self.module_name)
    59 
    60 class PermWrapper:
    61     def __init__(self, user):
    62         self.user = user
    63     def __getitem__(self, module_name):
    64         return PermLookupDict(self.user, module_name)
     54            processors = list(processors)
     55       
     56        for processor in processors + _standard_request_processors:
     57            self.update(processor(request))
  • django/core/processors.py

     
     1"""
     2A set of request processors that return dictionaries to be merged
     3into the context for templates.  Each function takes
     4
     5These are referenced from the setting REQUEST_PROCESSORS and used
     6in turn by DjangoContext
     7"""
     8
     9from django.conf.settings import DEBUG, INTERNAL_IPS, LANGUAGES, LANGUAGE_CODE
     10
     11def auth(request):
     12    """
     13    Returns a dictionary of context variables required by the
     14    admin app and other apps that use Django's authentication system.
     15    """
     16    return {
     17        'user': request.user,
     18        'messages': request.user.get_and_delete_messages(),
     19        'perms': PermWrapper(request.user),
     20    }
     21
     22def debug(request):
     23    """
     24    Returns a dictionary of context variables required
     25    for debugging.
     26    """
     27    context_extras = {}
     28    if DEBUG and request.META.get('REMOTE_ADDR') in INTERNAL_IPS:
     29        context_extras['debug'] = True
     30        from django.core import db
     31        context_extras['sql_queries'] = db.db.queries
     32    return context_extras
     33
     34def i18n(request):
     35    context_extras = {}
     36    context_extras['LANGUAGES'] = LANGUAGES
     37    if hasattr(request, 'LANGUAGE_CODE'):
     38        context_extras['LANGUAGE_CODE'] = request.LANGUAGE_CODE
     39    else:
     40        context_extras['LANGUAGE_CODE'] = LANGUAGE_CODE
     41    return context_extras
     42
     43# PermWrapper and PermLookupDict proxy the permissions system into objects that
     44# the template system can understand.
     45
     46class PermLookupDict:
     47    def __init__(self, user, module_name):
     48        self.user, self.module_name = user, module_name
     49    def __repr__(self):
     50        return str(self.user.get_permission_list())
     51    def __getitem__(self, perm_name):
     52        return self.user.has_perm("%s.%s" % (self.module_name, perm_name))
     53    def __nonzero__(self):
     54        return self.user.has_module_perms(self.module_name)
     55
     56class PermWrapper:
     57    def __init__(self, user):
     58        self.user = user
     59    def __getitem__(self, module_name):
     60        return PermLookupDict(self.user, module_name)
  • django/views/generic/date_based.py

     
    88
    99def archive_index(request, app_label, module_name, date_field, num_latest=15,
    1010                  template_name=None, template_loader=template_loader,
    11                   extra_lookup_kwargs={}, extra_context={}):
     11                  extra_lookup_kwargs={}, extra_context={}, processors=None):
    1212    """
    1313    Generic top-level archive of date-based objects.
    1414
     
    4141    c = Context(request, {
    4242        'date_list' : date_list,
    4343        'latest' : latest,
    44     })
     44    }, processors)
    4545    for key, value in extra_context.items():
    4646        if callable(value):
    4747            c[key] = value()
     
    5151
    5252def archive_year(request, year, app_label, module_name, date_field,
    5353                 template_name=None, template_loader=template_loader,
    54                  extra_lookup_kwargs={}, extra_context={}):
     54                 extra_lookup_kwargs={}, extra_context={}, processors=None):
    5555    """
    5656    Generic yearly archive view.
    5757
     
    7878    c = Context(request, {
    7979        'date_list': date_list,
    8080        'year': year,
    81     })
     81    }, processors)
    8282    for key, value in extra_context.items():
    8383        if callable(value):
    8484            c[key] = value()
     
    8888
    8989def archive_month(request, year, month, app_label, module_name, date_field,
    9090                  month_format='%b', template_name=None, template_loader=template_loader,
    91                   extra_lookup_kwargs={}, extra_context={}):
     91                  extra_lookup_kwargs={}, extra_context={}, processors=None):
    9292    """
    9393    Generic monthly archive view.
    9494
     
    130130    c = Context(request, {
    131131        'object_list': object_list,
    132132        'month': date,
    133     })
     133    }, processors)
    134134    for key, value in extra_context.items():
    135135        if callable(value):
    136136            c[key] = value()
     
    141141def archive_day(request, year, month, day, app_label, module_name, date_field,
    142142                month_format='%b', day_format='%d', template_name=None,
    143143                template_loader=template_loader, extra_lookup_kwargs={},
    144                 extra_context={}, allow_empty=False):
     144                extra_context={}, allow_empty=False, processors=None):
    145145    """
    146146    Generic daily archive view.
    147147
     
    181181        'day': date,
    182182        'previous_day': date - datetime.timedelta(days=1),
    183183        'next_day': (date < datetime.date.today()) and (date + datetime.timedelta(days=1)) or None,
    184     })
     184    }, processors)
    185185    for key, value in extra_context.items():
    186186        if callable(value):
    187187            c[key] = value()
     
    205205                  month_format='%b', day_format='%d', object_id=None, slug=None,
    206206                  slug_field=None, template_name=None, template_name_field=None,
    207207                  template_loader=template_loader, extra_lookup_kwargs={},
    208                   extra_context={}):
     208                  extra_context={}, processors=None):
    209209    """
    210210    Generic detail view from year/month/day/slug or year/month/day/id structure.
    211211
     
    247247        t = template_loader.get_template(template_name)
    248248    c = Context(request, {
    249249        'object': object,
    250     })
     250    }, processors)
    251251    for key, value in extra_context.items():
    252252        if callable(value):
    253253            c[key] = value()
  • django/views/generic/list_detail.py

     
    88
    99def object_list(request, app_label, module_name, paginate_by=None, allow_empty=False,
    1010                template_name=None, template_loader=template_loader,
    11                 extra_lookup_kwargs={}, extra_context={}):
     11                extra_lookup_kwargs={}, extra_context={}, processors=None):
    1212    """
    1313    Generic list of objects.
    1414
     
    5959            'previous': page - 1,
    6060            'pages': paginator.pages,
    6161            'hits' : paginator.hits,
    62         })
     62        }, processors)
    6363    else:
    6464        object_list = mod.get_list(**lookup_kwargs)
    6565        c = Context(request, {
    6666            'object_list': object_list,
    6767            'is_paginated': False
    68         })
     68        }, processors)
    6969        if len(object_list) == 0 and not allow_empty:
    7070            raise Http404
    7171    for key, value in extra_context.items():
     
    8181def object_detail(request, app_label, module_name, object_id=None, slug=None,
    8282                  slug_field=None, template_name=None, template_name_field=None,
    8383                  template_loader=template_loader, extra_lookup_kwargs={},
    84                   extra_context={}):
     84                  extra_context={}, processors=None):
    8585    """
    8686    Generic list of objects.
    8787
     
    112112        t = template_loader.get_template(template_name)
    113113    c = Context(request, {
    114114        'object': object,
    115     })
     115    }, processors)
    116116    for key, value in extra_context.items():
    117117        if callable(value):
    118118            c[key] = value()
  • django/views/generic/create_update.py

     
    99
    1010def create_object(request, app_label, module_name, template_name=None,
    1111                 template_loader=template_loader, extra_context={},
    12                  post_save_redirect=None, login_required=False, follow=None):
     12                 post_save_redirect=None, login_required=False, follow=None,
     13                 processors=None):
    1314    """
    1415    Generic object-creation function.
    1516   
     
    5859    t = template_loader.get_template(template_name)
    5960    c = Context(request, {
    6061        'form' : form,
    61     })
     62    }, processors)
    6263    for key, value in extra_context.items():
    6364        if callable(value):
    6465            c[key] = value()
     
    6970def update_object(request, app_label, module_name, object_id=None, slug=None,
    7071                  slug_field=None, template_name=None, template_loader=template_loader,
    7172                  extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
    72                   login_required=False, follow=None):
     73                  login_required=False, follow=None, processors=None):
    7374    """
    7475    Generic object-update function.
    7576
     
    130131    c = Context(request, {
    131132        'form' : form,
    132133        'object' : object,
    133     })
     134    }, processors)
    134135    for key, value in extra_context.items():
    135136        if callable(value):
    136137            c[key] = value()
     
    143144def delete_object(request, app_label, module_name, post_delete_redirect,
    144145                  object_id=None, slug=None, slug_field=None, template_name=None,
    145146                  template_loader=template_loader, extra_lookup_kwargs={},
    146                   extra_context={}, login_required=False):
     147                  extra_context={}, login_required=False, processors=None):
    147148    """
    148149    Generic object-delete function.
    149150   
     
    186187        t = template_loader.get_template(template_name)
    187188        c = Context(request, {
    188189            'object' : object,
    189         })
     190        }, processors)
    190191        for key, value in extra_context.items():
    191192            if callable(value):
    192193                c[key] = value()
  • docs/settings.txt

     
    478478only used if ``CommonMiddleware`` is installed (see the `middleware docs`_).
    479479See also ``APPEND_SLASH``.
    480480
     481REQUEST_PROCESSORS
     482------------------
     483
     484Default::
     485
     486    ("django.core.processors.auth",
     487     "django.core.processors.debug",
     488     "django.core.processors.i18n")
     489
     490A tuple of callables that are used by DjangoContext to populate itself. 
     491These callables take a request object as their argument and return a
     492dictionary of items to be merged into the context.
     493
    481494SECRET_KEY
    482495----------
    483496
  • docs/authentication.txt

     
    434434-----------
    435435
    436436The currently logged-in user's permissions are stored in the template variable
    437 ``{{ perms }}``. This is an instance of ``django.core.extensions.PermWrapper``,
     437``{{ perms }}``. This is an instance of ``django.core.processors.PermWrapper``,
    438438which is a template-friendly proxy of permissions.
    439439
    440440In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  • docs/templates_python.txt

     
    249249      logged in). See the `user authentication docs`.
    250250    * ``messages`` -- A list of ``auth.Message`` objects for the currently
    251251      logged-in user.
    252     * ``perms`` -- An instance of ``django.core.extensions.PermWrapper``,
     252    * ``perms`` -- An instance of ``django.core.processors.PermWrapper``,
    253253      representing the permissions that the currently logged-in user has. See
    254254      the `permissions docs`_.
    255255
Back to Top