Rails Style Controller

 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
# views.py file

import inspect 

from django.http import Http404, HttpResponse, HttpResponseRedirect

class BaseController(object):
    def __call__(self, request, url):
        parts = url.rstrip("/").split('/')
        
        try:
            view = parts.pop(0)
        except IndexError:
            raise Http404
        
        if view == "":
            view = "index"
            
        arg_count = len(parts)
        
        if hasattr(self, view):
            view_func = getattr(self, view)
            if callable(view_func):
                argspec = inspect.getargspec(view_func)
                func_arg_count = len(argspec[0]) - 2 # minus self, request
                if func_arg_count > arg_count:
                    if argspec[3] is not None:
                        default_count = len(argspec[3])
                        diff = func_arg_count - arg_count
                        if diff <= default_count:
                            parts = self.convert_args(view_func, parts)
                            return view_func(request, *parts)
                    raise Http404
                elif func_arg_count == arg_count:
                    parts = self.convert_args(view_func, parts)
                    return view_func(request, *parts)
        raise Http404

class MyController(BaseController):
    def index(self, request):
         return HttpResponse("Index")
    def help(self, request, slug=None):
        if not slug:
            return HttpResponse("Help Index")
        else:
            return HttpResponse("Slug")

# in urls.py

from my_app.views import MyController

urlpatterns = patterns('',
    url(r'^(.*)', MyController(), name='controller'),
)

More like this

  1. Add delete button in admin cp by cschand 6 years ago
  2. Use pexpect to control manage.py syncdb or anything else by aafshar 7 years, 1 month ago
  3. Filter users by fullname - postgresql by hamdiakoguz 3 years, 8 months ago
  4. Access Control Mechanisms with mod_wsgi by johnnoone 4 years, 2 months ago
  5. Django Twitter Bootstrap 3 pagination by Ragnar_Lodbrok 2 months, 3 weeks ago

Comments

anentropic (on September 21, 2009):

he means snippet #1204 :)

#

(Forgotten your password?)