Last active
August 29, 2015 13:57
-
-
Save w495/9836244 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def patch_class(clobj): | |
for method in ['get', 'put', 'post', 'delete', 'patch']: | |
if (hasattr(clobj, method)): | |
setattr(clobj, method, tresponse(getattr(clobj, method))) | |
return clobj | |
def tresponse(function): | |
''' | |
Adds `rest_framework.response.Response` with two parametrs | |
to initial function. | |
The first one is data of initial response. | |
The second one is the path to template. | |
This path can be described in View class attributes. | |
If it is not path calculates like this: | |
/<app_name>/<model_name>/<class_name>.html.djt | |
@param function is a method of View class, | |
which we want to decorate. | |
''' | |
if(not hasattr(function, 'has_tresponse')): | |
def _internal(self, request, *args, **kwargs): | |
response = function(self, request, *args, **kwargs) | |
_template_name = None | |
if(hasattr(self, 'template_name')): | |
_template_name = self.template_name | |
else: | |
_template_name = construct_template_name(self) | |
## | |
## We cannot use normal Django Middleware, | |
## cause we deal with Rest_framework request and response. | |
## (not Django's request\response) | |
## | |
if request.accepted_renderer.format == 'json': | |
request.accepted_renderer.charset = 'utf-8' | |
if request.accepted_renderer.format == 'html': | |
page = request.GET.get('page', 1); | |
search = request.GET.get('search', ""); | |
return Response( | |
{ | |
'data': response.data, | |
'meta': { | |
'request': request, | |
'page': page, | |
'search': search | |
} | |
}, | |
template_name=_template_name | |
) | |
return response | |
_internal.has_tresponse = True | |
return _internal | |
else: | |
return function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment