示例#1
0
def test_wtm_include_marketing(rf, site):
    token = Token(token_type=TOKEN_TYPE,
                  contents='wtm_include "marketing" "test.html"')
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    with pytest.raises(TemplateDoesNotExist):
        request = rf.get(site.root_page.url)
        node.render(context=make_context({"request": request}))

        request.COOKIES = {"wtm": "marketing:false"}
        node.render(context=make_context({"request": request}))

        request.COOKIES = {"wtm": "marketing:true"}
        node.render(context=make_context({"request": request}))
示例#2
0
    def call_render(self, func, template, context, *args, **kwargs):
        from django.template.context import make_context

        context = make_context(context, self._request)
        with context.bind_template(template.template):
            template.template._render(context)
            return func(context, *args, **kwargs)
示例#3
0
    def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 1.10 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango110Warning, stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango110Warning, stacklevel=2)

        else:
            context = make_context(context, request)

        return self.template.render(context)
示例#4
0
    def xmlrpc_handler(self, request):
        if settings.DEBUG:
            # clear queries to stop django allocating more and more memory
            # http://docs.djangoproject.com/en/dev/faq/models/#why-is-django-leaking-memory
            django.db.reset_queries()

        if request.method == "POST":
            return HttpResponse(self.xmlrpc_dispatcher._marshaled_dispatch(request), content_type="text/xml")
        else:
            method_list = []
            for method in self.xmlrpc_dispatcher.system_listMethods():
                method_list.append({
                    "name": method,
                    "signature": self.xmlrpc_dispatcher.system_methodSignature(method),
                    "help": self.xmlrpc_dispatcher.system_methodHelp(method).split("\n"),
                })

            c = {
                "title": "XML-RPC interface (%s)" % self.name,
                "method_list": method_list,
            }

            template = getattr(settings, "XMLRPC_TEMPLATE", None)
            if template is not None:
                t = loader.get_template(template)
                return HttpResponse(t.render(c, request))
            else:
                t = Template(XMLRPC_TEMPLATE, name="XML-RPC template")
                return HttpResponse(t.render(make_context(c, request=request)))
示例#5
0
    def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 1.10 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango110Warning, stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango110Warning, stacklevel=2)

        else:
            context = make_context(context, request)

        try:
            return self.template.render(context)
        except TemplateDoesNotExist as exc:
            reraise(exc, self.backend)
示例#6
0
 def render(self):
     context = make_context(self.get_context_data(), request=self.request)
     template = get_template(self.template_name)
     with context.bind_template(template.template):
         for node in template.template.nodelist:
             self._process_node(node, context)
     self._attach_body()
示例#7
0
def test_wtm_include_traceable(rf, site):
    token = Token(
        token_type=TokenType.TEXT, contents='wtm_include "traceable" "test.html"'
    )
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    with pytest.raises(TemplateDoesNotExist):
        request = rf.get(site.root_page.url)
        node.render(context=make_context({"request": request}))

        request.COOKIES = {"wtm_traceable": "false"}
        node.render(context=make_context({"request": request}))

        request.COOKIES = {"wtm_traceable": "true"}
        node.render(context=make_context({"request": request}))
示例#8
0
 def as_dict(self):
     '''
     Serialize the context as a dictionnary from a given request.
     '''
     data = {}
     if settings.JS_CONTEXT_ENABLED:
         template = get_template('djangojs/init.js')
         request_context = make_context({}, self.request)
         request_context.render_context.push()
         with request_context.bind_template(template.template):
             request_context.template_name = template.template.name
             for context in request_context:
                 for key, value in six.iteritems(context):
                     if settings.JS_CONTEXT and key not in settings.JS_CONTEXT:
                         continue
                     if settings.JS_CONTEXT_EXCLUDE and key in settings.JS_CONTEXT_EXCLUDE:
                         continue
                     handler_name = 'process_%s' % key
                     if hasattr(self, handler_name):
                         handler = getattr(self, handler_name)
                         data[key] = handler(value, data)
                     elif isinstance(value, SERIALIZABLE_TYPES) and not isinstance(value, SimpleLazyObject):
                         data[key] = value
     if settings.JS_USER_ENABLED:
         self.handle_user(data)
     # Monkey patch for https://github.com/noirbizarre/django.js/issues/53
     data.update({
         'STATIC_URL': settings.STATIC_URL,
         'MEDIA_URL': settings.MEDIA_URL,
         'LANGUAGES': settings.LANGUAGES,
         'LANGUAGE_CODE': getattr(self.request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE),
     })
     return data
示例#9
0
    def rendered_content(self):
        template = self._resolve_template(self.template_name)
        context = self._resolve_context(self.context_data)

        if not self.snippet_names and not self.force_snippets:
            content = template.render(context, self._request)
            return content

        context = make_context(context, self._request)
        with context.bind_template(template.template):
            template.template._render(context)
            snippets = {}

            for snippet_name in self.snippet_names:
                snippets[snippet_name] = self.render_snippet(template, context, snippet_name) or ''

        snippets.update(self.extra_snippets)

        for key, val in snippets.items():
            snippets[key] = clean_html(val)

        output = {
            'snippets': snippets,
        }

        output.update(self.extra_content)
        content = json.dumps(output)
        return content
示例#10
0
    def form_valid(self, form):
        if not self.request.is_ajax():
            return super(AjaxFormsCreateViewMixin, self).form_valid(form)

        super(AjaxFormsCreateViewMixin, self).form_valid(form)

        form_id = self.request.POST.get('ajax_form_id')
        context_data = {
            'object': self.object,
            'user': self.request.user,
            'created_with_ajax_forms': True,
        }
        if hasattr(self, 'ajax_result_partial_object_alias'):
            context_data[self.ajax_result_partial_object_alias] = self.object
        context = make_context(context_data, request=self.request).flatten()
        data = {
            'result_html':
            render_to_string(self.ajax_result_partial,
                             context,
                             request=self.request),
            'new_form_html':
            self.render_new_form(self.ajax_form_partial, form_id),
            'ajax_form_id':
            form_id,
            'messages':
            [force_text(msg) for msg in get_messages(self.request)
             ],  # this consumes the messages
        }
        return JsonResponse(data)
示例#11
0
    def render(self, context):
        request = context.get("request", None)
        if request:
            tag_config = TagTypeSettings().get(self.tag_type)

            if TagStrategy(request=request).should_include(
                    self.tag_type, tag_config):
                ctx_dict = Tag.create_context(request=request, context=context)
                ctx = make_context(ctx_dict, request)

                if self.src:
                    if self.src.endswith(".html"):
                        return render_to_string(self.src, ctx.flatten())

                    elif self.src.endswith(".css"):
                        tag = BeautifulSoup("", "html.parser").new_tag("link")
                        tag["rel"] = "stylesheet"
                        tag["type"] = "text/css"
                        tag["href"] = static(self.src)

                    elif self.src.endswith(".js"):
                        tag = BeautifulSoup("",
                                            "html.parser").new_tag("script")
                        tag["type"] = "text/javascript"
                        tag["src"] = static(self.src)

                    return mark_safe(tag.decode())

                output = self.nodelist.render(ctx)
                return output

        return ""
示例#12
0
def render_template_string(template_string, context=None,
                           request=None, using=None):
    if django_tag_re.findall(template_string):
        return Template(
            template_string=template_string, engine=using
        ).render(context=make_context(context=context, request=request))

    return template_string
 def render(self, context=None, request=None):
     context = make_context(context,
                            request,
                            autoescape=self.backend.engine.autoescape)
     try:
         return self.template.render(context)
     except TemplateDoesNotExist as exc:
         reraise(exc, self.backend)
示例#14
0
    def get_bricks_context(self):
        request = self.request
        context = make_context({}, request)

        for processor in Engine.get_default().template_context_processors:
            context.update(processor(request))

        return context
示例#15
0
 def rendered_content(self):
     template = self.resolve_template(self.template_name).template
     context = make_context(self.context_data, self._request)
     output = {}
     with context.bind_template(template):
         for n in template.nodelist.get_nodes_by_type(BlockNode):
             output[n.name] = n.render(context)
     return json.dumps(output)
示例#16
0
文件: email.py 项目: aarajh/draftt
 def render(self):
     context = make_context(self.get_context_data(), request=self.request)
     template = get_template(self.template_name)
     with context.bind_template(template.template):
         blocks = self._get_blocks(template.template.nodelist, context)
         for block_node in blocks.values():
             self._process_block(block_node, context)
     self._attach_body()
示例#17
0
    def render(self, context=None):
        template = get_template(self.subject)
        subject = template.template.render(
            make_context(context, autoescape=False))
        subject = "".join(subject.splitlines())

        body = render_to_string(self.body, context)

        return subject, body
示例#18
0
    def rendered_content(self):
        """
        Walk the template's node tree, casting our target blocks' nodelists to
        PJAXBlockNodeList in order to store its output in the render context.
        Then render the template as usual, but instead of returning the result,
        return the captured output from our target block(s).
        """

        # just for convenience
        block = self._djpj_block_name
        title_block = self._djpj_title_block_name
        title_var = self._djpj_title_variable

        # If no block name is specified, assume we're rendering a PJAX-specific
        # template and just return the rendered output.
        if not block:
            return super(PJAXTemplateResponse, self).rendered_content

        # Get a Template object
        template = self.resolve_template(self.template_name)

        # In Django 1.8, resolve_template doesn't return a django.template.Template
        # but rather a django.template.backends.django.Template which has a
        # django.template.Template as its "template" attribute. Template template.
        # Also, resolve_context returns a backend-agnostic dict, not a Context.
        if DJANGO_VERSION >= (1, 8):
            context = (make_context(
                self.context_data, self._request) if isinstance(
                    self.context_data, dict) else self.context_data)
            template = template.template
        else:
            context = self.resolve_context(self.context_data)

        # Otherwise, proceed to capture the output from the pjax block and,
        # if specified, the title block or variable.
        DjPjTemplate.patch(template)
        target_blocks = filter(None, (block, title_block))
        rendered_blocks = template.render_blocks(context, target_blocks)

        # Get all our error handling out of the way before generating
        # our PJAX-friendly output
        if None in rendered_blocks.values():
            raise TemplateSyntaxError(
                "Template block '%s' does not exist or was not rendered" %
                block)
        if title_var and title_var not in context:
            raise KeyError("PJAX title variable '%s' not found in context" %
                           title_var)

        # Return our PJAX response including a <title> tag if necessary
        block_contents = rendered_blocks[block]
        title_contents = rendered_blocks.get(title_block,
                                             None) or context.get(title_var)
        title_html = "<title>%s</title>\n" % title_contents if title_contents else ""

        return title_html + block_contents
示例#19
0
    def render(self, context=None, request=None):
        """
        Fills an odt template with the context obtained by combining the `context` and` request` \
parameters and returns an odt file as a byte object.
        """
        context = make_context(context, request)
        rendered = self.template.render(Context(context))
        odt_content = modify_zip_file(self.template_path, odt_handler,
                                      rendered)
        return odt_content
示例#20
0
def build_context(request, **kwargs):
    context = make_context({}, request)

    for processor in Engine.get_default().template_context_processors:
        context.update(processor(request))

    context.update(
        kwargs)  # Updated _after_ processors in order to avoid shadowing

    return context.flatten()
    def compatible_call_render(self, func, template, context, *args, **kwargs):
        if StrictVersion(django.get_version()) >= StrictVersion('1.8'):
            from django.template.context import make_context

            context = make_context(context, self._request)
            with context.bind_template(template.template):
                template.template._render(context)
                return func(template, context, *args, **kwargs)
        else:
            template._render(context)
            return func(template, context, *args, **kwargs)
示例#22
0
    def render(self, context=None, request=None):
        # self 是「最终模板对象」,context 是字典对象,request 是「请求对象」

        # 下面的 context 是 django.template.context.RequestContext 类的实例,叫做「请求上下文对象」
        context = make_context(context, request, autoescape=self.backend.engine.autoescape)
        try:
            # 此处调用「模板对象」的 render 方法返回携带渲染完毕的模板文件内容字符串的「响应体字符串对象」
            # 该对象是 django.utils.safestring.SafeString 类的实例
            return self.template.render(context)
        except TemplateDoesNotExist as exc:
            reraise(exc, self.backend)
示例#23
0
    def render(self, context=None, request=None):
        context = make_context(context, request)
        rendered = self.template.render(context)
        soup = BeautifulSoup(rendered, features='html.parser')
        soup = self.clean(soup)
        soup = self.replace_inputs(soup)
        soup = self.replace_pictures(soup, context)

        odt_content = modify_content_document(self.template_path, ['content.xml', 'styles.xml'], soup)
        for key, image in context.get('images', {}).items():
            odt_content = add_image_in_odt_template(odt_content, image, key)
        return odt_content
示例#24
0
 def render_cascade(self, context, tree_data):
     contents = []
     # create temporary copy of context to prevent pollution for other CMS placeholders
     context = make_context(flatten_context(context))
     for plugin_type, data, children_data in tree_data.get('plugins', []):
         plugin_class = strides_plugin_map.get(plugin_type)
         element_class = strides_element_map.get(plugin_type)
         plugin_instance = element_class(plugin_class(), data, children_data)
         # create a temporary object to store the plugins cache status
         cms_cachable_plugins = type(str('CachablePlugins'), (object,), {'value': True})
         context.push(cms_cachable_plugins=cms_cachable_plugins)
         contents.append(self.render_plugin(plugin_instance, context))
     return mark_safe(''.join(contents))
示例#25
0
def test_wtm_include_preferences(rf, site):
    expected_result = '<script src="/static/test.js" type="text/javascript"></script>'

    token = Token(token_type=TOKEN_TYPE,
                  contents='wtm_include "preferences" "test.js"')
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    request = rf.get(site.root_page.url)
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm": "preferences:false"}
    result = node.render(context=make_context({"request": request}))

    assert result == ""

    request.COOKIES = {"wtm": "preferences:true"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result
示例#26
0
def test_wtm_include_necessary(rf, site):
    expected_result = '<link href="/static/test.css" rel="stylesheet" type="text/css"/>'

    token = Token(token_type=TOKEN_TYPE,
                  contents='wtm_include "necessary" "test.css"')
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    request = rf.get(site.root_page.url)
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm": "necessary:false"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm": "necessary:true"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result
示例#27
0
    def rendered_content(self):
        template = self._resolve_template(self.template_name)
        context = self._resolve_context(self.context_data)

        if not self.snippet_names:
            return template.render(context, self._request)

        context = make_context(context, self._request)
        with context.bind_template(template.template):
            template.template._render(context)
            return self.render_snippet(template, context, self.snippet_names[0])

        return template.render(context, self._request)
示例#28
0
文件: template.py 项目: aibon/djpj
    def rendered_content(self):
        """
        Walk the template's node tree, casting our target blocks' nodelists to
        PJAXBlockNodeList in order to store its output in the render context.
        Then render the template as usual, but instead of returning the result,
        return the captured output from our target block(s).
        """

        # just for convenience
        block = self._djpj_block_name
        title_block = self._djpj_title_block_name
        title_var = self._djpj_title_variable

        # If no block name is specified, assume we're rendering a PJAX-specific
        # template and just return the rendered output.
        if not block:
            return super(PJAXTemplateResponse, self).rendered_content

        # Get a Template object
        template = self.resolve_template(self.template_name)

        # In Django 1.8, resolve_template doesn't return a django.template.Template
        # but rather a django.template.backends.django.Template which has a
        # django.template.Template as its "template" attribute. Template template.
        # Also, resolve_context returns a backend-agnostic dict, not a Context.
        if DJANGO_VERSION >= (1, 8):
            context = (make_context(self.context_data, self._request)
                       if isinstance(self.context_data, dict) else self.context_data)
            template = template.template
        else:
            context = self.resolve_context(self.context_data)

        # Otherwise, proceed to capture the output from the pjax block and,
        # if specified, the title block or variable.
        DjPjTemplate.patch(template)
        target_blocks = filter(None, (block, title_block))
        rendered_blocks = template.render_blocks(context, target_blocks)

        # Get all our error handling out of the way before generating
        # our PJAX-friendly output
        if None in rendered_blocks.values():
            raise TemplateSyntaxError("Template block '%s' does not exist or was not rendered" % block)
        if title_var and title_var not in context:
            raise KeyError("PJAX title variable '%s' not found in context" % title_var)

        # Return our PJAX response including a <title> tag if necessary
        block_contents = rendered_blocks[block]
        title_contents = rendered_blocks.get(title_block, None) or context.get(title_var)
        title_html = "<title>%s</title>\n" % title_contents if title_contents else ""

        return title_html + block_contents
示例#29
0
    def render_conf_file(self, filename, context=None, conf_filename=None):
        default_context = {"settings": settings, "config": config}
        if context is not None:
            default_context.update(context)

        template = get_template(f"services/{filename}")
        conf = template.template.render(
            make_context(default_context, autoescape=False))

        conf_filename = f"/config/{self.service_name}/{filename if conf_filename is None else conf_filename}"
        os.makedirs(os.path.dirname(conf_filename), exist_ok=True)
        with open(conf_filename, "w") as conf_file:
            conf_file.write(conf)
            logger.info(f"writing config file {conf_filename}")
示例#30
0
def test_wtm_include_functional(rf, site):
    expected_result = '<link href="/static/test.css" rel="stylesheet" type="text/css"/>'

    token = Token(
        token_type=TokenType.TEXT, contents='wtm_include "functional" "test.css"'
    )
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    request = rf.get(site.root_page.url)
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm_functional": "false"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm_functional": "true"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result
示例#31
0
def test_wtm_include_analytical(rf, site):
    expected_result = '<script src="/static/test.js" type="text/javascript"></script>'

    token = Token(
        token_type=TokenType.TEXT, contents='wtm_include "analytical" "test.js"'
    )
    parser = Parser(tokens=[token])
    node = wtm_include(parser, token)

    request = rf.get(site.root_page.url)
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result

    request.COOKIES = {"wtm_analytical": "false"}
    result = node.render(context=make_context({"request": request}))

    assert result == ""

    request.COOKIES = {"wtm_analytical": "true"}
    result = node.render(context=make_context({"request": request}))

    assert result == expected_result
示例#32
0
 def render(self, context=None, request=None):
     """
     Fills a docx template with the context obtained by combining the `context` and` request`
     parameters and returns a docx file as a byte object.
     """
     context = make_context(context, request)
     rendered = self.template.render(context)
     rendered = self.clean(rendered)
     soup = BeautifulSoup(rendered, features='html.parser')
     docx_content = modify_content_document(self.template_path,
                                            ['word/document.xml'], soup)
     for key, image in context.get('images', {}).items():
         docx_content = add_image_in_docx_template(docx_content, image)
     return docx_content
示例#33
0
    def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 2.0 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango20Warning,
                stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango20Warning,
                stacklevel=2)

        else:
            context = make_context(context, request)

        if hasattr(settings, 'MAKO_DEFAULT_CONTEXT'):
            context.dicts.append(settings.MAKO_DEFAULT_CONTEXT)

        context.dicts.append(default_context)
        try:
            with context.bind_template(self):
                return self.template.render(**context.flatten())
        except exceptions.TopLevelLookupException:
            raise
        except Exception as e:
            logging.error('Template Error\n request: %s\n context: %s',
                          request,
                          context,
                          exc_info=e)
            if settings.DEBUG:
                return exceptions.html_error_template().render()
            else:
                raise e
示例#34
0
    def render(self, context=None, request=None):
        base_url = self.get_base_url(request)
        if context is None:
            context = {}
        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

        html = weasyprint.HTML(
            string=self.template.render(make_context(context)),
            base_url=base_url,
        )
        html.render()
        return html.write_pdf()
    def render(self, request, contents, **kwargs):
        """Render *contents* using given *request*.

        The context data is represented by keyword arguments.
        Is no keyword arguments are provided, a default context will be used.

        Return the generated HTML and the modified context.
        """
        template = Template('{% load el_pagination_tags %}' + contents)
        context_data = kwargs.copy() if kwargs else {'objects': range(47)}
        context_data['request'] = request
        context = Context(context_data)
        if isinstance(context, dict):  # <-- my temporary workaround
            context = make_context(context, request, autoescape=self.backend.engine.autoescape)
        html = template.render(context)
        return html.strip(), context
示例#36
0
 def render(self, context=None, request=None):
     context_dict = make_context(context, request).flatten()
     output = None
     try:
         with NamedTemporaryFile('wb', suffix='.odt', delete=False) as f:
             output = f.name
             logger.debug("Render template '%s' to '%s'" % (self.path, output))
             renderer = Renderer(self.path, context_dict, output, overwriteExisting=True)
             renderer.run()
         result = open(output, 'rb').read()
     except (OSError, PodError) as e:
         logger.error("Cannot render '%s' : %s" % (self.path, e))
         raise OdtTemplateError(e)
     finally:
         if output and os.path.exists(output):
             os.unlink(output)
     return result
示例#37
0
    def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 2.0 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango20Warning, stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango20Warning, stacklevel=2)

        else:
            context = make_context(context, request)

        if hasattr(settings, 'MAKO_DEFAULT_CONTEXT'):
            context.dicts.append(settings.MAKO_DEFAULT_CONTEXT)

        context.dicts.append(default_context)
        try:
            with context.bind_template(self):
                return self.template.render(**context.flatten())
        except exceptions.TopLevelLookupException:
            raise
        except Exception as e:
            logging.error('Template Error\n request: %s\n context: %s', request, context, exc_info=e)
            if settings.DEBUG:
                return exceptions.html_error_template().render()
            else:
                raise e
示例#38
0
    def render(self, request, contents, **kwargs):
        """Render *contents* using given *request*.

        The context data is represented by keyword arguments.
        Is no keyword arguments are provided, a default context will be used.

        Return the generated HTML and the modified context.
        """
        template = Template('{% load el_pagination_tags %}' + contents)
        context_data = kwargs.copy() if kwargs else {'objects': range(47)}
        context_data['request'] = request
        context = Context(context_data)
        if isinstance(context, dict):  # <-- my temporary workaround
            context = make_context(context,
                                   request,
                                   autoescape=self.backend.engine.autoescape)
        html = template.render(context)
        return html.strip(), context
示例#39
0
 def render(self, context=None, request=None):
     context = make_context(context, request, autoescape=self.backend.engine.autoescape)
     try:
         return self.template.render(context)
     except TemplateDoesNotExist as exc:
         reraise(exc, self.backend)
示例#40
0
# Since this package contains a "django" module, this is required on Python 2.