Django view and url in one function

 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
# ======= /urls.py ==============

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^someurl/',include('someapp.url_view')), 
)

# ======= /someapp/url_view.py ==

from django.http import HttpResponse
from tourl import tourl


@tourl(r'^and/$')
def and_(request):
    return HttpResponse('and')

@tourl(r'^gg/$')
def index(request):
    return HttpResponse('OK')

# ======= /someapp/tourl.py ==

from django.conf.urls.defaults import *
import sys
import functools
def tourl(url_patern,*args,**kwargs):
    def paramed_decorator(func):
        @functools.wraps(func)
        def decorated(self):
            return func(self)
        module =sys.modules[func.__module__]
        
        if not hasattr(module, 'urlpatterns'):
            module.urlpatterns = patterns('',)
              
        module.urlpatterns   += patterns('',
            url(url_patern,decorated,*args,**kwargs), 
        )
        return decorated 
    return paramed_decorator

More like this

  1. @url decorator - getting rid of urlpatterns by southern_sun 6 years, 7 months ago
  2. Callable Class View by zbyte64 5 years, 11 months ago
  3. View Redirect Decorators by bryanpieper 3 years, 9 months ago
  4. Resolve URLs to view name by UloPe 5 years, 1 month ago
  5. Bit.ly url shortener by BluePeppers 3 years, 4 months ago

Comments

visik7 (on October 1, 2009):

why this ?

#

oduvan (on October 1, 2009):

instead creation someapp/urls.py ans someapp/views.py - you just using one file, which you all have

#

oduvan (on October 2, 2009):

revolunet, thank you for your suggestion. I add functools

#

(Forgotten your password?)