Login

Class that converts object to view.

Author:
Pickels
Posted:
May 30, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

Class that takes a normal none derived class and converts it into a view. The methods return simple datastructures which makes it easier to test.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class View(object):
    def __init__(self, controller):
        self.controller = controller()

    def as_template(self, template):

        def view(request, *args, **kwargs):
            return TemplateResponse( request, template, self.handler(request, *args, **kwargs) )

        return view

    def handler(self, request, *args, **kwargs):
        method = request.method.lower()
        handler = getattr(self.controller, method)
        return handler(request, *args, **kwargs) 

#Use a none derived class with http methods that return simple data structures. 

class HomeView(object):
    def get(self, request):
       return { 'foo' : 'bar' }

#In your url confs you can specify what the view returns. Only as_template is available.
url( r'^$', View(HomeView).as_template('home.html'), name='homepage' )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.