New Pattern

 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
####### file: newpatern/defaults.py #######

from django.conf.urls.defaults import url

class AddNewUrl(object):
    def __init__(self,prefix,view,*t):
        self.prefix = prefix
        self.view = view
        self.t = t
    def __call__(self,*t,**k):
        if 'before' in self.prefix :
            ret = self.prefix['before'](*t,**k)
            if ret:
                return ret
        ret =  self.view(*t,**k)
        if 'after' in self.prefix:
            self.prefix['after'](*t,**k)
        return ret

def newpatterns(prefix, *args):
    pattern_list = []
    for t in args:
        pattern_list.append(newurl(prefix, *t))
    return pattern_list

def newurl(prefix,regex,view,*t):
    return url(regex,AddNewUrl(prefix,view,*t),*t)


def classpatterns(cp):
    o_cp = cp()
    cp_prefix = {}
    if hasattr(o_cp,'before_cp'):
        before_cp = getattr(o_cp,'before_cp')
        if callable(before_cp):
            cp_prefix['before'] = before_cp
    func_list = ()
    for item in dir(o_cp):
        if item.startswith('cp__'):
            item_func = getattr(o_cp,item)
            if callable(item_func):
                func_list = func_list + ((r'^'+item[4:]+'/$',item_func),)
    #raise str(func_list)
    return newpatterns(cp_prefix,*func_list)


##### in your project ####################

##### file: ajax/vurls.py ################
from newpatern.defaults import newpatterns, classpatterns
from django.http import HttpResponse
class Views(object):
    def before__cp(self,request):
        pass #any code running before /test1 or /test2

    def cp__test1(self,request):
    	return HttpResponse('This is URL of TEST1!');
    
    def cp__test2(self,request):
    	return HttpResponse('This is URL of TEST2!');
    
    

urlpatterns = classpatterns(Views)


##### file: urls.py #####################
# just Add in you patterns list 
(r'^ajax/',include('ajax.vurls'))

#### Respons #####
# GET ajax/test1/
# Respons:This is URL of TEST1!

# GET ajax/test2/
# Respons:This is URL of TEST2!

More like this

  1. HTTPS redirections middleware with updated URL template tag by xlq 1 year, 6 months ago
  2. Conditional url pattern include by zbyte64 3 years, 8 months ago
  3. Resolve URLs to view name by UloPe 5 years, 1 month ago
  4. Ensure submitted slugs do not conflict with existing resolvable URLs by ElfSternberg 4 years, 9 months ago
  5. Django Breadcrumbs Snippet by flashingpumpkin 4 years, 11 months ago

Comments

daevaorn (on November 26, 2008):

Looks a bit ugly.

#

Oduvan (on November 26, 2008):

Using newpatterns you can write more expandable code

#

(Forgotten your password?)