- Author:
- southern_sun
- Posted:
- August 29, 2007
- Language:
- Python
- Version:
- .96
- 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
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Looks interesting. I think it makes sense for really huge projects.
#
Please login first before commenting.