Login

Django view and url in one function

Author:
oduvan
Posted:
October 1, 2009
Language:
Python
Version:
1.1
Score:
-3 (after 7 ratings)

application 'someapp' don't have urls.py file, all information about urls placed as decorator for view function

PS: Added functools.wraps

 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. 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, 2 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

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

#

Please login first before commenting.