@url decorator improvements

 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 7 months, 3 weeks ago
  2. Using reverse() to do redirects by ubernostrum 6 years, 8 months ago
  3. Complex Formsets, Redux by smagala 4 years, 1 month ago
  4. @url decorator - getting rid of urlpatterns by southern_sun 6 years, 8 months ago
  5. Improved Pickled Object Field by taavi223 4 years, 8 months ago

Comments

(Forgotten your password?)