Login

Class that converts object to view.

Author:
Pickels
Posted:
May 30, 2011
Language:
Python
Version:
1.3
Tags:
views test
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. Class based view decorator by robcharlwood 3 years, 8 months ago
  2. HTML to POST dict converter by guettli 7 years, 5 months ago
  3. Automatic testing of add and changelist admin views by Taifu 3 years, 8 months ago
  4. RequestFactory: Easily create mock request objects, for use in testing by simon 6 years, 8 months ago
  5. Lazy Man's Django test case by prestontimmons 3 years, 5 months ago

Comments

Please login first before commenting.