Prettify the HTML response.

        :param response: A Flask Response object.
764147
def _prettify_response(self, response):
        
        if response.content_type == 'text/html; charset=utf-8':
            ugly = response.get_data(as_text=True)
            soup = BeautifulSoup(ugly, 'html.parser')
            pretty = soup.prettify(formatter='html')
            response.direct_passthrough = False
            response.set_data(pretty)

        return response
733983
def respond(template, context={}, request=None, **kwargs):
    ""
    from django.http import HttpResponse
    from django.template import RequestContext
    from django.template.loader import render_to_string    

    if request:
        default = context_processors.default(request)
        default.update(context)
    else:
        default = context.copy()
    
    rendered = render_to_string(template, default, context_instance=request and RequestContext(request) or None)
    return HttpResponse(rendered, **kwargs)
421173
def clean_response(response):
    
    response = re.sub("^['\"]", "", response)
    response = re.sub("['\"]$", "", response)
    return response
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
964202
def format_response(status, body_object, headers={})
      if status == 204
        body = ''
      else
        body = case response_media_type
        when 'application/json'
          JSON.pretty_generate(body_object)
        when 'application/x-www-form-urlencoded'
          URI.encode_www_form(body_object)
        when 'application/xml'
          body_object.to_s
        when 'text/plain'
          body_object
        else
          # :nocov:
          raise NotImplementedError, "unsupported response media type #{response_media_type}"
          # :nocov:
        end
      end
      [status, headers.merge({'Content-Type' => response_media_type}), [body]]
    end
1058466
def prettyfy(response, format='json'):
    
    if format == 'json':
        return pretty_json(response.content)
    else:
        return pretty_xml(response.content)
734154
def render_django_response(self, **kwargs):
        """"""
        from django.http import HttpResponse
        return HttpResponse(
            self.render(**kwargs), content_type='image/svg+xml'
        )
245792
def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
    """"""

    if 'no_template' in meta and meta['no_template']:  # Just send the json back
        return HttpResponse(result)

    # TODO this breaks pages not using new template
    # Add sidebar toggler if plugit did not add by itself
    # if not "sidebar-toggler" in result:
    #     result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result

    # render the template into the whole page
    if not settings.PIAPI_STANDALONE:
        return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(),
                                  {"project": hproject,
                                   "plugit_content": result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    if proxyMode:  # Force inclusion inside template
        return render_to_response('plugIt/base.html',
                                  {'plugit_content': result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    renderPlugItTemplate = 'plugItBase.html'
    if settings.PIAPI_PLUGITTEMPLATE:
        renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE

    return render_to_response('plugIt/' + renderPlugItTemplate,
                              {"plugit_content": result,
                               "plugit_menu": menu,
                               'context': context},
                              context_instance=RequestContext(request))
263407
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None):
        ''''''
        template_adapter = self.get_template_loader(subdir).get_template(template)
        return getattr(template_adapter, 'render_to_response')(context=context, request=self.request, def_name=def_name, content_type=content_type, status=status, charset=charset)
943493
def _build_response(data, renderer=None):
    
    if isinstance(data, Response) or isinstance(data, BaseResponse):
        return data
    if not renderer:
        raise AttributeError(" Renderer is required")
    if isinstance(data, dict) or data is None:
        data = {} if data is None else data
        for _ in __view_parsers:
            data = _(data)
        return renderer(data), 200
    elif isinstance(data, tuple):
        data, status, headers = _normalize_response_tuple(data)
        for _ in __view_parsers:
            data = _(data)
        return renderer(data or {}), status, headers
    return data
828901
def response_hook(self, response, **kwargs) -> HTMLResponse:
        
        if not response.encoding:
            response.encoding = DEFAULT_ENCODING
        return HTMLResponse._from_response(response, self)
689476
def render_to_response(self, context, **response_kwargs):
        
        context["ajax_form_id"] = self.ajax_form_id
        # context["base_template"] = "towel_bootstrap/modal.html"
        return self.response_class(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            **response_kwargs
        )
1071668
def wrap_httplib_response(response_func):
    

    def call(self, *args, **kwargs):
        _tracer = execution_context.get_opencensus_tracer()
        current_span_id = execution_context.get_opencensus_attr(
            'httplib/current_span_id')

        span = _tracer.current_span()

        # No corresponding request span is found, request not traced.
        if not span or span.span_id != current_span_id:
            return response_func(self, *args, **kwargs)

        result = response_func(self, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status))

        _tracer.end_span()
        return result

    return call
480977
def render_to_response(self, context, **response_kwargs):
        
        filename = os.path.basename(self.object.file.name)

        # Try to guess the content type of the given file
        content_type, _ = mimetypes.guess_type(self.object.file.name)
        if not content_type:
            content_type = 'text/plain'

        response = HttpResponse(self.object.file, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename={}'.format(filename)

        return response
1108054
def response_minify(self, response):
        

        if response.content_type == u'text/html; charset=utf-8':
            endpoint = request.endpoint or ''
            view_func = current_app.view_functions.get(endpoint, None)
            name = (
                '%s.%s' % (view_func.__module__, view_func.__name__)
                if view_func else ''
            )
            if name in self._exempt_routes:
                return response

            response.direct_passthrough = False
            response.set_data(
                self._html_minify.minify(response.get_data(as_text=True))
            )

            return response
        return response
990749
def prettify_object(obj):
    """"""

    try:
        return pprint.pformat(str(obj))
    except UnicodeDecodeError as e:
        raise
    except Exception as e:
        return "[could not display: <%s: %s>]" % (e.__class__.__name__, str(e))
208107
def prettify_json(json_string):
    """"""
    try:
        data = json.loads(json_string)
        html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
    except:
        html = json_string
    return mark_safe(html)