예제 #1
0
def _render(template, callable_, args, data, as_unicode=False):
    """create a Context and return the string
    output of the given template and template callable."""

    if as_unicode:
        buf = util.FastEncodingBuffer(as_unicode=True)
    elif template.bytestring_passthrough:
        buf = compat.StringIO()
    else:
        buf = util.FastEncodingBuffer(
            as_unicode=as_unicode,
            encoding=template.output_encoding,
            errors=template.encoding_errors,
        )
    context = Context(buf, **data)
    context._outputting_as_unicode = as_unicode
    context._set_with_template(template)

    _render_context(
        template,
        callable_,
        context,
        *args,
        **_kwargs_for_callable(callable_, data)
    )
    return context._pop_buffer().getvalue()
예제 #2
0
def _render(template, callable_, args, data, as_unicode=False):
    """create a Context and return the string output of the given template and template callable."""
    if as_unicode:
        buf = util.FastEncodingBuffer()
    elif template.output_encoding:
        buf = util.FastEncodingBuffer(template.output_encoding,
                                      template.encoding_errors)
    else:
        buf = util.StringIO()
    context = Context(buf, **data)
    context._with_template = template
    _render_context(template, callable_, context, *args,
                    **_kwargs_for_callable(callable_, data))
    return context.pop_buffer().getvalue()
예제 #3
0
def compile(node,
            uri,
            filename=None,
            default_filters=None,
            buffer_filters=None,
            imports=None,
            future_imports=None,
            source_encoding=None,
            generate_magic_comment=True,
            disable_unicode=False,
            strict_undefined=False,
            enable_loop=True,
            reserved_names=frozenset()):
    """Generate module source code given a parsetree node,
      uri, and optional source filename"""

    # if on Py2K, push the "source_encoding" string to be
    # a bytestring itself, as we will be embedding it into
    # the generated source and we don't want to coerce the
    # result into a unicode object, in "disable_unicode" mode
    if not compat.py3k and isinstance(source_encoding, compat.text_type):
        source_encoding = source_encoding.encode(source_encoding)

    buf = util.FastEncodingBuffer()

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(
        printer,
        _CompileContext(uri, filename, default_filters, buffer_filters,
                        imports, future_imports, source_encoding,
                        generate_magic_comment, disable_unicode,
                        strict_undefined, enable_loop, reserved_names), node)
    return buf.getvalue()
예제 #4
0
    def _push_writer(self):
        """push a capturing buffer onto this Context and return
        the new writer function."""

        buf = util.FastEncodingBuffer()
        self._buffer_stack.append(buf)
        return buf.write
예제 #5
0
def _render_error(template, context, error):
    if template.error_handler:
        result = template.error_handler(context, error)
        if not result:
            raise error
    else:
        error_template = exceptions.html_error_template()
        if context._outputting_as_unicode:
            context._buffer_stack[:] = [util.FastEncodingBuffer(unicode=True)]
        else:
            context._buffer_stack[:] = [util.FastEncodingBuffer(
                                            error_template.output_encoding,
                                            error_template.encoding_errors)]
 
        context._with_template = error_template
        error_template.render_context(context, error=error)
예제 #6
0
 def test_fast_buffer_encoded(self):
     s = u"drôl m’a rée « S’il"
     buf = util.FastEncodingBuffer(encoding='utf-8')
     buf.write(s[0:10])
     buf.write(s[10:])
     q = buf.getvalue()
     eq_(buf.getvalue(), s.encode('utf-8'))
예제 #7
0
def compile(node, uri, filename=None, default_filters=None, buffer_filters=None, imports=None, source_encoding=None, generate_unicode=True):
    """generate module source code given a parsetree node, uri, and optional source filename"""

    buf = util.FastEncodingBuffer(unicode=generate_unicode)

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(printer, _CompileContext(uri, filename, default_filters, buffer_filters, imports, source_encoding, generate_unicode), node)
    return buf.getvalue()
예제 #8
0
 def test_fast_buffer_truncate(self):
     buf = util.FastEncodingBuffer()
     buf.write("string a ")
     buf.write("string b")
     buf.truncate()
     buf.write("string c ")
     buf.write("string d")
     eq_(buf.getvalue(), "string c string d")
예제 #9
0
def _render_error(template, context, error):
    if template.error_handler:
        result = template.error_handler(context, error)
        if not result:
            compat.reraise(*sys.exc_info())
    else:
        error_template = exceptions.html_error_template()
        if context._outputting_as_unicode:
            context._buffer_stack[:] = [
                util.FastEncodingBuffer(as_unicode=True)
            ]
        else:
            context._buffer_stack[:] = [
                util.FastEncodingBuffer(
                    error_template.output_encoding,
                    error_template.encoding_errors,
                )
            ]

        context._set_with_template(error_template)
        error_template.render_context(context, error=error)
예제 #10
0
def _render_error(template, context, error):
    if template.error_handler:
        result = template.error_handler(context, error)
        if not result:
            tp, value, tb = sys.exc_info()
            if value and tb:
                raise value.with_traceback(tb)
            else:
                raise error
    else:
        error_template = exceptions.html_error_template()
        if context._outputting_as_unicode:
            context._buffer_stack[:] = [util.FastEncodingBuffer()]
        else:
            context._buffer_stack[:] = [
                util.FastEncodingBuffer(
                    error_template.output_encoding,
                    error_template.encoding_errors,
                )
            ]

        context._set_with_template(error_template)
        error_template.render_context(context, error=error)
예제 #11
0
파일: view.py 프로젝트: tru-software/tru
 def load_template(self):
     if not self.__mako_template or settings.MAKO_ALWAYS_RELOAD:
         if not self.__mako_lookup:
             self.__build()
         # To załaduje sam plik mako
         try:
             self.__mako_template = self.__mako_lookup.get_template(
                 self.__mako_filename)
             # natomiast trzeba jeszcze załadować nadrzędne mako
             tmp_context = mako_runtime.Context(
                 mako_util.FastEncodingBuffer())
             tmp_context._with_template = self.__mako_template
             mako_runtime._populate_self_namespace(tmp_context,
                                                   self.__mako_template)
         except Exception as ex:
             log.error("Cannot load template: %s (%s) in %s: %s" %
                       (self.__mako_filename, self.__mako_template.module
                        if self.__mako_template else 'file not found',
                        self.__mako_lookup.directories, ex))
             # print "Cannot load template: %s (%s)" % (self.__mako_filename, self.__mako_template.module if self.__mako_template else 'file not found')
             raise
예제 #12
0
def compile(  # noqa
    node,
    uri,
    filename=None,
    default_filters=None,
    buffer_filters=None,
    imports=None,
    future_imports=None,
    source_encoding=None,
    generate_magic_comment=True,
    strict_undefined=False,
    enable_loop=True,
    reserved_names=frozenset(),
):
    """Generate module source code given a parsetree node,
    uri, and optional source filename"""

    buf = util.FastEncodingBuffer()

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(
        printer,
        _CompileContext(
            uri,
            filename,
            default_filters,
            buffer_filters,
            imports,
            future_imports,
            source_encoding,
            generate_magic_comment,
            strict_undefined,
            enable_loop,
            reserved_names,
        ),
        node,
    )
    return buf.getvalue()
예제 #13
0
 def test_fast_buffer_encoded(self):
     s = u("drôl m’a rée « S’il")
     buf = util.FastEncodingBuffer(encoding="utf-8")
     buf.write(s[0:10])
     buf.write(s[10:])
     eq_(buf.getvalue(), s.encode("utf-8"))
예제 #14
0
    the contextual Template will be located if it exists, and the error handling options specified
    on that Template will be interpreted here.
    """
    template = context._with_template
    if template is not None and (template.format_exceptions
                                 or template.error_handler):
        error = None
        try:
            callable_(context, *args, **kwargs)
        except Exception, e:
            error = e
        except:
            e = sys.exc_info()[0]
            error = e
        if error:
            if template.error_handler:
                result = template.error_handler(context, error)
                if not result:
                    raise error
            else:
                error_template = exceptions.html_error_template()
                context._buffer_stack[:] = [
                    util.FastEncodingBuffer(error_template.output_encoding,
                                            error_template.encoding_errors)
                ]
                context._with_template = error_template
                error_template.render_context(context, error=error)
    else:
        callable_(context, *args, **kwargs)
예제 #15
0
        _exec_template(callable_, context, args=args, kwargs=kwargs)
        
def _exec_template(callable_, context, args=None, kwargs=None):
    """execute a rendering callable given the callable, a Context, and optional explicit arguments

    the contextual Template will be located if it exists, and the error handling options specified
    on that Template will be interpreted here.
    """
    template = context._with_template
    if template is not None and (template.format_exceptions or template.error_handler):
        error = None
        try:
            callable_(context, *args, **kwargs)
        except Exception, e:
            error = e
        except:                
            e = sys.exc_info()[0]
            error = e
        if error:
            if template.error_handler:
                result = template.error_handler(context, error)
                if not result:
                    raise error
            else:
                error_template = exceptions.html_error_template()
                context._buffer_stack[:] = [util.FastEncodingBuffer(error_template.output_encoding, error_template.encoding_errors)]
                context._with_template = error_template
                error_template.render_context(context, error=error)
    else:
        callable_(context, *args, **kwargs)
예제 #16
0
 def push_buffer(self):
     """push a capturing buffer onto this Context."""
     self._buffer_stack.append(util.FastEncodingBuffer())