Login

simple_view

Author:
troolee
Posted:
June 30, 2010
Language:
Python
Version:
Not specified
Score:
0 (after 2 ratings)

Simplify views declararation. (Upd: add assertion)

 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
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext


def simple_view(template, mimetype='text/html'):
    '''
    Simplify views declararation.
    
    Usage:
    
    @simple_view('path/to/template.html')
    def view1(request):
        ...
        return {
            'context_var1': context_var1,
        }
    
    @simple_view('path/to/template.txt', mimetype='text/plain')
    def view2(request):
        pass # it's ok to return nothing     
    
    @simple_view('path/to/template.html')
    def view3(request):
        if some_condition:
            return redirect('view1') # You could return HttpResponse object
        return {}
    '''
    def decorator(func):
        def real_decorator(request, *args, **kwargs):
            returned = func(request, *args, **kwargs)
            if isinstance(returned, HttpResponse):
                return returned
            assert returned is None or isinstance(returned, dict)
            return render_to_response(template,
                                      returned or {},
                                      context_instance=RequestContext(request))
        return real_decorator
    return decorator

More like this

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

Comments

troolee (on July 1, 2010):

@buriy yep, with a little modification - view is able to return HttpResponse except of dict

#

troolee (on July 1, 2010):

@buriy it's pretty useful when you want to make redirection inside of the view

#

Please login first before commenting.