def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response: Union[HttpResponse, StreamingHttpResponse] = self.get_response(request) if not response.streaming: try: data = json.loads(response.content) transformed_data = { 'status': response.status_code, 'data': data } transformed_bytes = json.dumps(transformed_data).encode( 'utf-8') new_response = HttpResponse(transformed_bytes, status=response.status_code) _headers = { k: v for k, v in response._headers.items() if k != 'content-length' } new_response._headers = {**new_response._headers, **_headers} new_response.cookies = response.cookies return new_response except Exception as e: pass # Code to be executed for each request/response after # the view is called. return response
def wrapper(*args, **kwargs): response = func(*args, **kwargs) json_response = HttpResponse(content_type='application/json') if isinstance(response, HttpResponse): json_response.cookies = response.cookies json_response.status_code = response.status_code if isinstance(response, (HttpResponseRedirect, HttpResponsePermanentRedirect)): json = {'redirect': response['Location']} else: json = {'html': response.content} else: json = response json_response.write(simplejson.dumps(json)) return json_response
def json(self, process_url=None): ''' Returns the content as a json object be parsed and loaded in javascript @param process_url: url of the application to be loaded ''' if process_url is not None: self.process_url = process_url application_content = self._build_content() if isinstance(application_content, AMPCMSAjaxResponse): response = application_content.response elif isinstance(application_content, HttpResponseFullRedirect): response = HttpResponse(json.dumps({C.JSON_KEY_REDIRECT: True, C.JSON_KEY_NAME: self._data_model.name, C.JSON_KEY_LOCATION: application_content['location'], C.JSON_KEY_HTML: '', C.JSON_KEY_CSS: self._build_css(), C.JSON_KEY_JS: self._build_js()})) elif isinstance(application_content, HttpResponseRedirect) \ or isinstance(application_content, HttpFixedResponse): response = application_content else: html = self.html(include_content=application_content) response = HttpResponse(json.dumps({C.JSON_KEY_REDIRECT: False, C.JSON_KEY_NAME: self._data_model.name, C.JSON_KEY_LOCATION: self.process_url, C.JSON_KEY_HTML: Markup(html), C.JSON_KEY_CSS: self._build_css(), C.JSON_KEY_JS: self._build_js(), C.JSON_KEY_MESSAGES : [ {'message': message.message.decode('utf8'), 'level': message.level, 'tags': message.tags} for message in messages.get_messages(self.request)] })) if self.response is not None and len(self.response.cookies) > 0: response.cookies = self.response.cookies return response