@url decorator - getting rid of urlpatterns

 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 2 years, 5 months ago
  2. SSL Middleware by sjzabel 7 years, 1 month ago
  3. Generic AJAX app by Rupe 4 years, 9 months ago
  4. A action decorator for URLs by Batiste 6 years ago
  5. Automatic urls for static pages by jibbolo 3 years, 5 months ago

Comments

mikeivanov (on August 30, 2007):

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

#

(Forgotten your password?)