Python mako.exceptions.text_error_template() Examples

The following are 30 code examples of mako.exceptions.text_error_template(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mako.exceptions , or try the search function .
Example #1
Source File: pyfiles.py    From android_universal with MIT License 6 votes vote down vote up
def template_to_file(template_file, dest, output_encoding, **kw):
    template = Template(filename=template_file)
    try:
        output = template.render_unicode(**kw).encode(output_encoding)
    except:
        with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as ntf:
            ntf.write(
                exceptions.text_error_template().
                render_unicode().encode(output_encoding))
            fname = ntf.name
        raise CommandError(
            "Template rendering failed; see %s for a "
            "template-oriented traceback." % fname)
    else:
        with open(dest, 'wb') as f:
            f.write(output) 
Example #2
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_module_block_line_number(self):
        l = TemplateLookup()
        l.put_string(
            "foo.html",
            """
<%!
def foo():
    msg = "Something went wrong."
    raise RuntimeError(msg)  # This is the line.
%>
${foo()}
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'File "foo.html", line 7, in render_body' in text_error
            assert 'File "foo.html", line 5, in foo' in text_error
            assert "raise RuntimeError(msg)  # This is the line." in text_error
        else:
            assert False 
Example #3
Source File: test_exceptions.py    From mako with MIT License 6 votes vote down vote up
def test_code_block_line_number(self):
        l = TemplateLookup()
        l.put_string(
            "foo.html",
            """
<%
msg = "Something went wrong."
raise RuntimeError(msg)  # This is the line.
%>
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'File "foo.html", line 4, in render_body' in text_error
            assert "raise RuntimeError(msg)  # This is the line." in text_error
        else:
            assert False 
Example #4
Source File: pyfiles.py    From alembic with MIT License 6 votes vote down vote up
def template_to_file(template_file, dest, output_encoding, **kw):
    template = Template(filename=template_file)
    try:
        output = template.render_unicode(**kw).encode(output_encoding)
    except:
        with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as ntf:
            ntf.write(
                exceptions.text_error_template()
                .render_unicode()
                .encode(output_encoding)
            )
            fname = ntf.name
        raise CommandError(
            "Template rendering failed; see %s for a "
            "template-oriented traceback." % fname
        )
    else:
        with open(dest, "wb") as f:
            f.write(output) 
Example #5
Source File: pyfiles.py    From jbox with MIT License 6 votes vote down vote up
def template_to_file(template_file, dest, output_encoding, **kw):
    template = Template(filename=template_file)
    try:
        output = template.render_unicode(**kw).encode(output_encoding)
    except:
        with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as ntf:
            ntf.write(
                exceptions.text_error_template().
                render_unicode().encode(output_encoding))
            fname = ntf.name
        raise CommandError(
            "Template rendering failed; see %s for a "
            "template-oriented traceback." % fname)
    else:
        with open(dest, 'wb') as f:
            f.write(output) 
Example #6
Source File: cmd.py    From ansible-cmdb with GNU General Public License v3.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #7
Source File: cmd.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #8
Source File: test_exceptions.py    From docassemble with MIT License 5 votes vote down vote up
def test_text_error_template(self):
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render_unicode()
            assert False
        except exceptions.CompileException:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'Traceback (most recent call last):' in text_error
            assert ("CompileException: Fragment 'i = 0' is not a partial "
                    "control statement") in text_error 
Example #9
Source File: __init__.py    From pdoc with GNU Affero General Public License v3.0 5 votes vote down vote up
def _render_template(template_name, **kwargs):
    """
    Returns the Mako template with the given name.  If the template
    cannot be found, a nicer error message is displayed.
    """
    # Apply config.mako configuration
    MAKO_INTERNALS = Template('').module.__dict__.keys()
    DEFAULT_CONFIG = path.join(path.dirname(__file__), 'templates', 'config.mako')
    config = {}
    for config_module in (Template(filename=DEFAULT_CONFIG).module,
                          tpl_lookup.get_template('/config.mako').module):
        config.update((var, getattr(config_module, var, None))
                      for var in config_module.__dict__
                      if var not in MAKO_INTERNALS)
    known_keys = (set(config)
                  | {'docformat'}  # Feature. https://github.com/pdoc3/pdoc/issues/169
                  | {'module', 'modules', 'http_server', 'external_links'})  # deprecated
    invalid_keys = {k: v for k, v in kwargs.items() if k not in known_keys}
    if invalid_keys:
        warn('Unknown configuration variables (not in config.mako): {}'.format(invalid_keys))
    config.update(kwargs)

    try:
        t = tpl_lookup.get_template(template_name)
    except TopLevelLookupException:
        raise OSError(
            "No template found at any of: {}".format(
                ', '.join(path.join(p, template_name.lstrip("/"))
                          for p in tpl_lookup.directories)))
    try:
        return t.render(**config).strip()
    except Exception:
        from mako import exceptions
        print(exceptions.text_error_template().render(),
              file=sys.stderr)
        raise 
Example #10
Source File: utils.py    From deepcontext with MIT License 5 votes vote down vote up
def mkorendertpl(tpl,outfile,*args,**kwargs):
  with open(outfile,"w") as f:
    try:
      f.write(tpl.render(*args,**kwargs));
    except:
      print((exceptions.text_error_template().render()))
      raise; 
Example #11
Source File: cmd.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #12
Source File: router.py    From FibbingNode with GNU General Public License v2.0 5 votes vote down vote up
def render(template, dest, **kwargs):
        """
        Render a Mako template passing it optional arguments
        """
        log.debug('Generating %s\n' % dest)
        try:
            text = Template(filename=template).render(**kwargs)
            with closing(open(dest, 'w')) as f:
                f.write(text)
        except:
            # Display template errors in a less cryptic way
            log.error('Couldn''t render a config file (%s)',
                      os.path.basename(template))
            log.error(exceptions.text_error_template().render()) 
Example #13
Source File: cmd.py    From android_universal with MIT License 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #14
Source File: __init__.py    From binja_sensei with MIT License 5 votes vote down vote up
def render(bv):
    try:
        show_markdown_report("{} Writeup".format(name), template.render(bv=bv, images=images))
    except:
        show_plain_text_report("{}: Error in Rendering".format(name), exceptions.text_error_template().render()) 
Example #15
Source File: code_generator_utils.py    From nnabla with Apache License 2.0 5 votes vote down vote up
def render_with_template(text=None, filename=None, preprocessor=None, template_kwargs={}):
    from mako.template import Template
    from mako import exceptions

    tmpl = Template(text=text, filename=filename, preprocessor=preprocessor)
    try:
        return tmpl.render(**template_kwargs)
    except Exception as e:
        import sys
        print('-' * 78, file=sys.stderr)
        print('Template exceptions', file=sys.stderr)
        print('-' * 78, file=sys.stderr)
        print(exceptions.text_error_template().render(), file=sys.stderr)
        print('-' * 78, file=sys.stderr)
        raise e 
Example #16
Source File: __init__.py    From binja_sensei with MIT License 5 votes vote down vote up
def render(bv):
    try:
        show_markdown_report("{} Writeup".format(name), template.render(bv=bv, images=images))
    except:
        show_plain_text_report("{}: Error in Rendering".format(name), exceptions.text_error_template().render()) 
Example #17
Source File: __init__.py    From binja_sensei with MIT License 5 votes vote down vote up
def render(bv):
    try:
        show_markdown_report("{} Writeup".format(name), template.render(bv=bv))
    except:
        show_plain_text_report("{}: Error in Rendering".format(name), exceptions.text_error_template().render()) 
Example #18
Source File: __init__.py    From binja_sensei with MIT License 5 votes vote down vote up
def render(bv):
    try:
        show_markdown_report("{} Writeup".format(name), template.render(bv=bv))
    except:
        show_plain_text_report("{}: Error in Rendering".format(name), exceptions.text_error_template().render()) 
Example #19
Source File: __init__.py    From binja_sensei with MIT License 5 votes vote down vote up
def render(bv):
    try:
        show_markdown_report("{} Writeup".format(name), template.render(bv=bv))
    except:
        show_plain_text_report("{}: Error in Rendering".format(name), exceptions.text_error_template().render()) 
Example #20
Source File: cmd.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #21
Source File: templates.py    From pyA2L with GNU General Public License v2.0 5 votes vote down vote up
def doTemplateFromText(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'):
    buf = StringIO()
    ctx = Context(buf, **namespace)
    try:
        tobj = Template(text = tmpl, output_encoding = encoding, format_exceptions = formatExceptions) #, imports ='re'
        tobj.render_context(ctx)
    except:
        print(exceptions.text_error_template().render())
        return None
    return indentText(buf.getvalue(), leftMargin) #, rightMargin) 
Example #22
Source File: templates.py    From pyA2L with GNU General Public License v2.0 5 votes vote down vote up
def doTemplate(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'):
    buf = StringIO()
    ctx = Context(buf, **namespace)
    try:
        tobj = Template(filename = tmpl, output_encoding = encoding,  format_exceptions = formatExceptions) #, imports ='re' # TODO: imports parameter.
        tobj.render_context(ctx)
    except:
        print(exceptions.text_error_template().render())
        return None
    ##return strings.reformat(buf.getvalue(), leftMargin, rightMargin)
    return buf.getvalue() 
Example #23
Source File: test_exceptions.py    From mako with MIT License 5 votes vote down vote up
def test_alternating_file_names(self):
        l = TemplateLookup()
        l.put_string(
            "base.html",
            """
<%!
def broken():
    raise RuntimeError("Something went wrong.")
%> body starts here
<%block name="foo">
    ${broken()}
</%block>
            """,
        )
        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
<%block name="foo">
    ${parent.foo()}
</%block>
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert """
  File "base.html", line 5, in render_body
    %> body starts here
  File "foo.html", line 4, in render_foo
    ${parent.foo()}
  File "base.html", line 7, in render_foo
    ${broken()}
  File "base.html", line 4, in broken
    raise RuntimeError("Something went wrong.")
""" in text_error
        else:
            assert False 
Example #24
Source File: test_exceptions.py    From mako with MIT License 5 votes vote down vote up
def test_text_error_template(self):
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render_unicode()
            assert False
        except exceptions.CompileException:
            text_error = exceptions.text_error_template().render_unicode()
            assert "Traceback (most recent call last):" in text_error
            assert (
                "CompileException: Fragment 'i = 0' is not a partial "
                "control statement"
            ) in text_error 
Example #25
Source File: cmd.py    From mako with MIT License 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #26
Source File: __init__.py    From aiohttp-mako with Apache License 2.0 5 votes vote down vote up
def render_string(template_name, request, context, *, app_key):
    lookup = request.app.get(app_key)

    if lookup is None:
        raise web.HTTPInternalServerError(
            text=("Template engine is not initialized, "
                  "call aiohttp_mako.setup(app_key={}) first"
                  "".format(app_key)))
    try:
        template = lookup.get_template(template_name)
    except TemplateLookupException as e:
        raise web.HTTPInternalServerError(
            text="Template '{}' not found".format(template_name)) from e
    if not isinstance(context, Mapping):
        raise web.HTTPInternalServerError(
            text="context should be mapping, not {}".format(type(context)))
    if request.get(REQUEST_CONTEXT_KEY):
        context = dict(request[REQUEST_CONTEXT_KEY], **context)
    try:
        text = template.render_unicode(**context)
    except Exception:  # pragma: no cover
        exc_info = sys.exc_info()
        errtext = text_error_template().render(
            error=exc_info[1],
            traceback=exc_info[2])
        exc = MakoRenderingException(errtext).with_traceback(exc_info[2])
        raise exc

    return text 
Example #27
Source File: cmd.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #28
Source File: cmd.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #29
Source File: cmd.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1) 
Example #30
Source File: cmd.py    From jbox with MIT License 5 votes vote down vote up
def _exit():
    sys.stderr.write(exceptions.text_error_template().render())
    sys.exit(1)