Python jinja2.DictLoader() Examples

The following are 30 code examples of jinja2.DictLoader(). 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 jinja2 , or try the search function .
Example #1
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_class_based_view(aiohttp_client):
    class MyView(web.View):
        @aiohttp_jinja2.template('tmpl.jinja2')
        async def get(self):
            return {'head': 'HEAD', 'text': 'text'}

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', MyView)

    client = await aiohttp_client(app)

    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #2
Source File: test_jinjasql.py    From jinjasql with MIT License 6 votes vote down vote up
def test_import(self):
        utils = """
        {% macro print_where(value) -%}
        WHERE dummy_col = {{value}}
        {%- endmacro %}
        """
        source = """
        {% import 'utils.sql' as utils %}
        select * from dual {{ utils.print_where(100) }}
        """
        loader = DictLoader({"utils.sql" : utils})
        env = Environment(loader=loader)

        j = JinjaSql(env)
        query, bind_params = j.prepare_query(source, _DATA)
        expected_query = "select * from dual WHERE dummy_col = %s"
        self.assertEquals(query.strip(), expected_query.strip())
        self.assertEquals(len(bind_params), 1)
        self.assertEquals(list(bind_params)[0], 100) 
Example #3
Source File: test_jinja_filters.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_jinja_filters(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def index(request):
        return {}

    def add_2(value):
        return value + 2

    app = web.Application()
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.DictLoader({'tmpl.jinja2': "{{ 5|add_2 }}"}),
        filters={'add_2': add_2}
    )

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '7' == txt 
Example #4
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_skip_render_for_response_from_handler(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return web.Response(text='OK')

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': '{{text}}'}))

    app.router.add_route('GET', '/', func)

    client = await aiohttp_client(app)
    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert 'OK' == txt 
Example #5
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_can_disable_autoescape(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return {'text': '<script>alert(1)</script>'}

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': '<html>{{text}}</html>'}), autoescape=False)

    app.router.add_route('GET', '/', func)

    client = await aiohttp_client(app)
    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><script>alert(1)</script></html>' == txt 
Example #6
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_without_context(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        pass

    template = '<html><body><p>{{text}}</p></body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': template}))

    app.router.add_route('GET', '/', func)

    client = await aiohttp_client(app)
    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><p></p></body></html>' == txt 
Example #7
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_mapping():

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return 123

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': 'tmpl'}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "context should be mapping, not <class 'int'>"
    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #8
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_template_not_found():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    t = "Template 'template' not found"
    assert t == ctx.value.text
    assert t == ctx.value.reason 
Example #9
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_template_custom_status(aiohttp_client):

    async def func(request):
        return aiohttp_jinja2.render_template(
            'tmpl.jinja2', request,
            {'head': 'HEAD', 'text': 'text'}, status=404)

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', func)

    client = await aiohttp_client(app)

    resp = await client.get('/')

    assert 404 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #10
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_template(aiohttp_client):

    async def func(request):
        return aiohttp_jinja2.render_template(
            'tmpl.jinja2', request,
            {'head': 'HEAD', 'text': 'text'})

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', func)

    client = await aiohttp_client(app)

    resp = await client.get('/')

    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #11
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_convert_func_to_coroutine(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return {'head': 'HEAD', 'text': 'text'}

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', func)

    client = await aiohttp_client(app)

    resp = await client.get('/')

    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #12
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_func(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return {'head': 'HEAD', 'text': 'text'}

    template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'
    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
        'tmpl.jinja2': template
    }))

    app.router.add_route('*', '/', func)

    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '<html><body><h1>HEAD</h1>text</body></html>' == txt 
Example #13
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_static_var_missing(aiohttp_client, caplog):

    async def index(request):
        with pytest.raises(RuntimeError, match='static_root_url'):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ static('whatever.js') }}"}))

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status  # static_root_url is not set 
Example #14
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_helpers_disabled(aiohttp_client):

    async def index(request):
        with pytest.raises(jinja2.UndefinedError,
                           match="'url' is undefined"):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    app = web.Application()
    aiohttp_jinja2.setup(
        app,
        default_helpers=False,
        loader=jinja2.DictLoader(
            {'tmpl.jinja2': "{{ url('index')}}"})
    )

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status 
Example #15
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_url_param_forbidden_type(aiohttp_client):

    async def index(request):
        with pytest.raises(TypeError,
                           match=(r"argument value should be str or int, "
                                  r"got arg -> \[<class 'bool'>\] True")):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    async def other(request):
        return

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('other', arg=True)}}"}))

    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/uid/{arg}', other, name='other')
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status 
Example #16
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_url_int_param(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def index(request):
        return {}

    async def other(request):
        return

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('other', arg=1)}}"}))

    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/uid/{arg}', other, name='other')
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '/uid/1' == txt 
Example #17
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_url_with_query(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def index(request):
        return {}

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('index', query_={'foo': 'bar'})}}"}))

    app.router.add_get('/', index, name='index')
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '/?foo=bar' == txt 
Example #18
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_url(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def index(request):
        return {}

    async def other(request):
        return

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2':
         "{{ url('other', name='John_Doe')}}"}))

    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/user/{name}', other, name='other')
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status
    txt = await resp.text()
    assert '/user/John_Doe' == txt 
Example #19
Source File: inheritance.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_scoped_block_after_inheritance(self):
        env = Environment(loader=DictLoader({
            'layout.html': '''
            {% block useless %}{% endblock %}
            ''',
            'index.html': '''
            {%- extends 'layout.html' %}
            {% from 'helpers.html' import foo with context %}
            {% block useless %}
                {% for x in [1, 2, 3] %}
                    {% block testing scoped %}
                        {{ foo(x) }}
                    {% endblock %}
                {% endfor %}
            {% endblock %}
            ''',
            'helpers.html': '''
            {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}
            '''
        }))
        rv = env.get_template('index.html').render(the_foo=42).split()
        assert rv == ['43', '44', '45'] 
Example #20
Source File: inheritance.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_scoped_block_after_inheritance(self):
        env = Environment(loader=DictLoader({
            'layout.html': '''
            {% block useless %}{% endblock %}
            ''',
            'index.html': '''
            {%- extends 'layout.html' %}
            {% from 'helpers.html' import foo with context %}
            {% block useless %}
                {% for x in [1, 2, 3] %}
                    {% block testing scoped %}
                        {{ foo(x) }}
                    {% endblock %}
                {% endfor %}
            {% endblock %}
            ''',
            'helpers.html': '''
            {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}
            '''
        }))
        rv = env.get_template('index.html').render(the_foo=42).split()
        assert rv == ['43', '44', '45'] 
Example #21
Source File: inheritance.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_scoped_block_after_inheritance(self):
        env = Environment(loader=DictLoader({
            'layout.html': '''
            {% block useless %}{% endblock %}
            ''',
            'index.html': '''
            {%- extends 'layout.html' %}
            {% from 'helpers.html' import foo with context %}
            {% block useless %}
                {% for x in [1, 2, 3] %}
                    {% block testing scoped %}
                        {{ foo(x) }}
                    {% endblock %}
                {% endfor %}
            {% endblock %}
            ''',
            'helpers.html': '''
            {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}
            '''
        }))
        rv = env.get_template('index.html').render(the_foo=42).split()
        assert rv == ['43', '44', '45'] 
Example #22
Source File: page.py    From dactyl with MIT License 5 votes vote down vote up
def load_from_generator(self):
        """
        Load the text from a generator function,
        as either raw text or a jinja template.
        Assume no frontmatter in this case.
        """
        if not self.skip_pp:
            pp_env = self.get_pp_env(
                loader=jinja2.DictLoader({"_": self.data["__md_generator"]()}) )
            self.pp_template = pp_env.get_template("_")
        else:
            self.rawtext = self.data["__md_generator"]() 
Example #23
Source File: templating.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_custom_template_loader(self):
        class MyFlask(flask.Flask):
            def create_global_jinja_loader(self):
                from jinja2 import DictLoader
                return DictLoader({'index.html': 'Hello Custom World!'})
        app = MyFlask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('index.html')
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello Custom World!') 
Example #24
Source File: templating.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_custom_template_loader(self):
        class MyFlask(flask.Flask):
            def create_global_jinja_loader(self):
                from jinja2 import DictLoader
                return DictLoader({'index.html': 'Hello Custom World!'})
        app = MyFlask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('index.html')
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello Custom World!') 
Example #25
Source File: templating.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_custom_template_loader(self):
        class MyFlask(flask.Flask):
            def create_global_jinja_loader(self):
                from jinja2 import DictLoader
                return DictLoader({'index.html': 'Hello Custom World!'})
        app = MyFlask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('index.html')
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello Custom World!') 
Example #26
Source File: inheritance.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_dynamic_inheritance(self):
        env = Environment(loader=DictLoader({
            'master1': 'MASTER1{% block x %}{% endblock %}',
            'master2': 'MASTER2{% block x %}{% endblock %}',
            'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
        }))
        tmpl = env.get_template('child')
        for m in range(1, 3):
            assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m 
Example #27
Source File: make_changelog.py    From landlab with MIT License 5 votes vote down vote up
def main():
    tags = releases(ascending=False)
    changelog = OrderedDict()
    release_date = dict()
    for start, stop in zip(tags[1:], tags[:-1]):
        changes = brief(start=start, stop=stop)
        if changes:
            changelog[stop] = group_changes(changes)
            release_date[stop] = git_tag_date(stop)

    env = jinja2.Environment(loader=jinja2.DictLoader({'changelog': CHANGELOG}))
    print(env.get_template('changelog').render(releases=changelog,
                                               release_date=release_date)) 
Example #28
Source File: inheritance.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_super(self):
        env = Environment(loader=DictLoader({
            'a': '{% block intro %}INTRO{% endblock %}|'
                 'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
            'b': '{% extends "a" %}{% block data %}({{ '
                 'super() }}){% endblock %}',
            'c': '{% extends "b" %}{% block intro %}--{{ '
                 'super() }}--{% endblock %}\n{% block data '
                 '%}[{{ super() }}]{% endblock %}'
        }))
        tmpl = env.get_template('c')
        assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER' 
Example #29
Source File: inheritance.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_preserve_blocks(self):
        env = Environment(loader=DictLoader({
            'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
            'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
        }))
        tmpl = env.get_template('b')
        assert tmpl.render() == 'BA' 
Example #30
Source File: inheritance.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_dynamic_inheritance(self):
        env = Environment(loader=DictLoader({
            'master1': 'MASTER1{% block x %}{% endblock %}',
            'master2': 'MASTER2{% block x %}{% endblock %}',
            'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
        }))
        tmpl = env.get_template('child')
        for m in range(1, 3):
            assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m