1 | #Idea and implementation by Anton Berezin
|
---|
2 |
|
---|
3 | from django.http import HttpResponse, HttpRequest
|
---|
4 | from django.template import loader
|
---|
5 | from django.template import RequestContext
|
---|
6 | import re #regexp
|
---|
7 |
|
---|
8 |
|
---|
9 | #The response object that can hold the context
|
---|
10 | class HttpResponseHolder(HttpResponse):
|
---|
11 | context = {} #make sure that it is a dictianory
|
---|
12 |
|
---|
13 |
|
---|
14 | #Adds a template to a view, uses context processors
|
---|
15 | class template(object):
|
---|
16 |
|
---|
17 | def __init__(self, template_name = None):
|
---|
18 | self.template_name = template_name
|
---|
19 |
|
---|
20 | def __call__(self, function):
|
---|
21 | def function_wrapper(request, *args, **kwargs):
|
---|
22 | return_val = function(request, *args, **kwargs)
|
---|
23 | #get a proper template name
|
---|
24 | if self.template_name == None: #if template name is not defined derive it from package name and view function name
|
---|
25 | array = re.split("\.", function.__module__) #split into array with elements like [0]=project_name, [1]=package_name, [2]=file_name (where the function lives)
|
---|
26 | package_name = array[1]
|
---|
27 | self.template_name = "%s/%s.html" %(package_name, function.__name__)
|
---|
28 | #compose the response
|
---|
29 | template = loader.get_template(str(self.template_name))
|
---|
30 | if isinstance(return_val, HttpResponseHolder):
|
---|
31 | return HttpResponse(template.render(RequestContext(request, return_val.context)))
|
---|
32 | elif isinstance(return_val, dict):
|
---|
33 | return HttpResponse(template.render(RequestContext(request, return_val)))
|
---|
34 | elif isinstance(return_val, HttpResponse):
|
---|
35 | return return_val
|
---|
36 | else:
|
---|
37 | return
|
---|
38 | return function_wrapper
|
---|