Login

@url decorator improvements

Author:
davepeck
Posted:
August 6, 2009
Language:
Python
Version:
1.1
Tags:
urls url decorator decorators urlpatterns
Score:
1 (after 1 ratings)

A slight modification (and, I think, improvement) of the URL decorator found in snippet 395.

What's different between this snippet and 395?

  1. We use django.conf.urls.defaults.url() when adding patterns
  2. We support arbitrary arguments to the url() method (like name="foo")
  3. We do not support multiple url patterns (this didn't seem useful to me, but if it is I can add it back.)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import sys

from django.core.urlresolvers import RegexURLResolver
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url as dcud_url

#
# Annotate a view with the URL that points to it
#

def url(pattern, *args, **kwargs):
    """
    Usage:
    @url(r'^users$')
    def get_user_list(request):
        ...
        
    @url(r'^info/(.*)/$', name="url-name") 
    @render_to('wiki.html')
    def wiki(request, title=''):
        ...
    """
    caller_filename = sys._getframe(1).f_code.co_filename
    module = None
    for m in sys.modules.values():
        if m and '__file__' in m.__dict__ and m.__file__.startswith(caller_filename):
            module = m
            break
    def _wrapper(f):
        if module:
            if 'urlpatterns' not in module.__dict__:
                module.urlpatterns = []
            module.urlpatterns += patterns('', dcud_url(pattern, f, *args, **kwargs))
        return f
    return _wrapper

#
# Continue the @url decorator pattern into sub-modules, if desired
#

def include_urlpatterns(regex, module):
    """
    Usage:
    
    # in top-level module code:
    urlpatterns = include_urlpatterns(r'^profile/', 'apps.myapp.views.profile')
    """
    return [RegexURLResolver(regex, module)]

More like this

  1. Accessing URL variable from within a Form by blacktav 1 year, 11 months ago
  2. Using reverse() to do redirects by ubernostrum 7 years, 11 months ago
  3. Complex Formsets, Redux by smagala 5 years, 4 months ago
  4. @url decorator - getting rid of urlpatterns by southern_sun 7 years, 11 months ago
  5. Improved Pickled Object Field by taavi223 5 years, 11 months ago

Comments

Please login first before commenting.