Beispiel #1
0
    def render(self, request, context, template_name):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        self.set_renderers(request)

        for renderer in request.renderers:
            response = renderer(self, request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(
                itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None
        for key, value in additional_headers.iteritems():
            response[key] = value

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept', ))
        return response
Beispiel #2
0
    def render(self, request=None, context=None, template_name=None):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        request, context, template_name = self.get_render_params(request, context, template_name)

        self.set_renderers()

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in request.renderers:
            response = renderer(request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None
        for key, value in additional_headers.iteritems():
            response[key] = value

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept',))
        return response
Beispiel #3
0
    def getRenderer(self, format, mimetypes, name, priority):
        if not isinstance(mimetypes, tuple):
            mimetypes = (mimetypes,)

        def renderer(request, context, template_name):
            return HttpResponse("", mimetype=mimetypes[0])

        renderer.__name__ = "render_%s" % mimetypes[0].replace("/", "_")
        renderer = decorators.renderer(format=format, mimetypes=mimetypes, priority=priority)(renderer)
        return renderer
Beispiel #4
0
    def render(self, request, context, template_name):
        # We save context and template
        # in the instance so we can retrieve them
        # when cycling over all alternates.
        self._template_used = template_name
        self._context_used = context

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        if not hasattr(request, 'renderers'):
            request.renderers = self.get_renderers(request)

        for renderer in request.renderers:
            response = renderer(self, request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            self._not_acceptable = True


        # Transparent Content Negotiation
        # TODO properly, we should only do it if we're serving
        # HTTP/1.1, and not for 1.0 --> self._tcn_enabled flag

        if self._tcn_enabled:
            if getattr(self, '_tcn', False):
                additional_headers['Alternates'] = self.get_alternates_header()
                if self._server_choice:
                    additional_headers['TCN'] = "choice"
                else:
                    additional_headers['TCN'] = "list"
                    self._multiple_choices = True

        if self._need_variant_list():
            response = self._get_variant_list()

        for key, value in additional_headers.iteritems():
            response[key] = value

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header (and negotiate
        # if we're doing it)

        varying = ("Accept",)
        if self._tcn_enabled:
            varying = varying + ("Negotiate",)
        patch_vary_headers(response, varying)
        return response
Beispiel #5
0
 def _get_dot_renderer(output):
     def dot_renderer(self, request, context, template_name):
         layout = request.GET.get('layout')
         if layout not in self._DOT_LAYOUTS:
             layout = 'fdp'
         template = loader.get_template(template_name + '.gv')
         plain_gv = template.render(RequestContext(request, context))
         dot = subprocess.Popen(['dot', '-K'+layout, '-T'+dot_output], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
         dot_stdout, _ = dot.communicate(input=plain_gv.encode('utf-8'))
         response = HttpResponse(dot_stdout, mimetype=output['mimetypes'][0])
         response['Content-Disposition'] = 'inline; filename="%s.%s"' % (slugify(context['subject'].dcterms_title)[:32], output['format'])
         return response
     
     dot_output = output.pop('dot_output')
     dot_renderer.__name__ = 'render_%s' % output['format']
     return renderer(**output)(dot_renderer)
    def render(self, request, context, template_name):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        request, context, template_name = self.get_render_params(
            request, context, template_name)
        self.set_renderers()

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in request.renderers:
            response = renderer(request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(
                itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None

        for key, value in additional_headers.items():
            # My changes -- Modify location for 303 redirect
            if key == 'location' and response.renderer:
                location = '%s.%s/' % (value, response.renderer.format)
                try:
                    #location += '?page=%s' % context['page']
                    location += '?{}'.format(context['queries'])
                except KeyError:
                    pass
                response[key] = location
            else:
                response[key] = value
            # End my changes

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept', ))
        return response
Beispiel #7
0
    def render_to_format(self, request, context, template_name, format):
        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in self._renderers_by_format.get(format, ()):
            response = renderer(self, request, context, template_name)
            if response is not NotImplemented:
                break
        else:
            response = self.http_not_acceptable(request, ())
            renderer = None

        response.status_code = status_code
        response.renderer = renderer
        for key, value in additional_headers.iteritems():
            response[key] = value
        return response
Beispiel #8
0
    def render(self, request, context, template_name):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        request, context, template_name = self.get_render_params(request, context, template_name)
        self.set_renderers()

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in request.renderers:
            response = renderer(request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None

        for key, value in additional_headers.items():

            # My changes -- Modify location for 303 redirect
            if key == 'location' and response.renderer:
                location = '%s.%s/' % (value, response.renderer.format)
                try:
                    # location += '?page=%s' % context['page']
                    location += '?{}'.format(context['queries'])
                except KeyError:
                    pass
                response[key] = location
            else:
                response[key] = value
            # End my changes
        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept',))
        return response
Beispiel #9
0
    def override_redirect(self, request, description_url, mimetypes):
        url = urlparse.urlparse(description_url)
        if 'django_hosts' in settings.INSTALLED_APPS:
            host, _ = self.hosts_middleware.get_host(url.netloc)
            urlconf = host.urlconf
        else:
            urlconf = None

        try:
            view, _, _ = resolve(url.path, urlconf)
        except Resolver404:
            return False

        should_redirect = lambda: True
        renderer = decorators.renderer(None, mimetypes, float('inf'), None)(should_redirect)

        accepts = self.parse_accept_header(request.META.get('HTTP_ACCEPT', ''))
        renderers = MediaType.resolve(accepts, (renderer,) + view.conneg.renderers)

        return renderers and renderers[0] is should_redirect
Beispiel #10
0
    def _get_dot_renderer(output):
        def dot_renderer(self, request, context, template_name):
            layout = request.GET.get('layout')
            if layout not in self._DOT_LAYOUTS:
                layout = 'fdp'
            template = loader.get_template(template_name + '.gv')
            plain_gv = template.render(RequestContext(request, context))
            dot = subprocess.Popen(['dot', '-K' + layout, '-T' + dot_output],
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE)
            dot_stdout, _ = dot.communicate(input=plain_gv.encode('utf-8'))
            response = HttpResponse(dot_stdout,
                                    mimetype=output['mimetypes'][0])
            response[
                'Content-Disposition'] = 'inline; filename="{0}.{1}"'.format(
                    context['filename_base'], output['format'])
            return response

        dot_output = output.pop('dot_output')
        dot_renderer.__name__ = 'render_%s' % output['format']
        return renderer(**output)(dot_renderer)
Beispiel #11
0
    def override_redirect(self, request, description_url, mimetypes):
        url = urlparse.urlparse(description_url)
        if 'django_hosts' in settings.INSTALLED_APPS:
            host, _ = self.hosts_middleware.get_host(url.netloc)
            urlconf = host.urlconf
        else:
            urlconf = None

        try:
            view, _, _ = resolve(url.path, urlconf)
        except Resolver404:
            return False

        should_redirect = lambda: True
        renderer = decorators.renderer(None, mimetypes, float('inf'),
                                       None)(should_redirect)

        accepts = self.parse_accept_header(request.META.get('HTTP_ACCEPT', ''))
        renderers = MediaType.resolve(accepts,
                                      (renderer, ) + view.conneg.renderers)

        return renderers and renderers[0] is should_redirect