Login

@url decorator improvements

Author:
davepeck
Posted:
August 6, 2009
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.