Login

@url decorator - getting rid of urlpatterns

Author:
southern_sun
Posted:
August 29, 2007
Language:
Python
Version:
.96
Tags:
view url decorator urlpatterns
Score:
6 (after 6 ratings)

The rationale behind this decorator is described in django-users google group.

Usage:

=== urls.py ===
urlpatterns = patterns('',
    (r'^', include('apps.app1.views')),
    (r'^app2', include('apps.app2.views')),
)

=== apps/app1/views/__init__.py ===
@url(r'^index/$')
    def index(request):
    ...

@url(r'^news/$')
def news(request):
    ...

urlpatterns += include_urlpatterns(r'^members', 'apps.app1.views.members')

=== apps/app1/views/members.py ===
@url(r'^profile/$)
def profile(request):
    ....

@url(r'^secure/$)
def secure(request):
    ...

@url(r'^path1/$', '^path2/$') # you can specify several patterns
def multipath_view(request):
    ...

def helper(): # easily distinguishable - no @url!
    ...

Summarizing, the benefits are:

  • no more creating and supporting urlpattern maps (less files, less code, more DRY)
  • have the url associated with a view in-place
  • easily see if a function is a view
  • fully compatible with other chained decorators
 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
import sys

from django.core.urlresolvers import RegexURLResolver
from django.conf.urls.defaults import patterns

def url(*args):
	"""
	Usage:
	@url(r'^users$')
	def get_user_list(request):
		...
		
	@url(r'^info/$', r'^info/(.*)/$') # will match both
	@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 = []
			for pattern in args:
				module.urlpatterns += patterns('',(pattern,f))
		return f
	return _wrapper

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. Decorate every view in a url tree by sjzabel 3 years, 6 months ago
  2. SSL Middleware by sjzabel 8 years, 2 months ago
  3. Generic AJAX app by Rupe 5 years, 11 months ago
  4. A action decorator for URLs by Batiste 7 years, 1 month ago
  5. Automatic urls for static pages by jibbolo 4 years, 6 months ago

Comments

mikeivanov (on August 30, 2007):

Looks interesting. I think it makes sense for really huge projects.

#

Please login first before commenting.