Just a quick hack for a Controller style pattern. Similar to the approach taken in django.contrib.admin views
things this breaks: 1. {% url %} and reverse() 2. validation provided by regex urlpatterns
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
he means snippet #1204 :)
#
Please login first before commenting.