Using class methods as views

 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
from django.conf.urls.defaults import patterns, url
from django.http import HttpResponse

def resource_handler(request, handler_class, handler_suffix, method_param = "__method__", *args, **kwargs):
    method      = request.GET[method_param] if method_param in request.GET else request.method
    method      = method.lower()
    methodname  = method + "_handler_" + handler_suffix
    themethod   = getattr(handler_class, methodname, None)
    if themethod:
        return themethod(request, *args, **kwargs)
    else:
        raise Http404

def handler_params(cls, suffix):
    return {'handler_class': cls, 'handler_suffix': suffix}

class HandlerA(object):
    @classmethod
    def get_handler_objects(cls, request, id = None):
        if id:
            return HttpResponse("You have requested object of id: %s" % id)
        else:
            return HttpResponse("You have requesting listing og objecta")

    @classmethod
    def put_handler_objects(cls, request):
        return HttpResponse("You are creating a new object")

    @classmethod
    def post_handler_objects(cls, request, id):
        return HttpResponse("You are updating object of id: %s" % id)

    @classmethod
    def delete_handler_objects(cls, request, id):
        return HttpResponse("You are deleting object of id: %s" % id)

urlpatterns = patterns('',
    # front page
    url(r'obja/$', resource_handler, handler_params(HandlerA, "objects"), name="list_of_objecta"),
    url(r'obja/create/$', resource_handler, handler_params(HandlerA, "objects"), name="objecta_create"),
    url(r'obja/(?P<id>[^\/]+)/$', resource_handler, handler_params(HandlerA, "objects"), name="objecta_details"),
    url(r'obja/(?P<id>[^\/]+)/delete/$', resource_handler, handler_params(HandlerA, "objects"), name="objecta_delete"),
    url(r'obja/(?P<id>[^\/]+)/update/$', resource_handler, handler_params(HandlerA, "objects"), name="objecta_update"),
)

More like this

  1. FieldAccessForm (per-field user access for forms derived from models) by Killarny 5 years, 6 months ago
  2. Declaring django views like web.py views by danigm 4 years, 2 months ago
  3. Resource by zvoase 5 years, 6 months ago
  4. RFC: Shim to allow view classes rather than functions by peterbraden 5 years, 1 month ago
  5. Effective content caching for mass-load site using redirect feature by nnseva 2 years, 9 months ago

Comments

(Forgotten your password?)