aiohttp_mako

mako template renderer for aiohttp.web. aiohttp_mako based on aiohttp_jinja2. Library has almost same api and it is used in aiohttp_debugtoolbar.

Usage

Before template rendering you have to setup mako templates location first:

app = web.Application(loop=loop)
lookup = aiohttp_mako.setup(app, input_encoding='utf-8',
                            output_encoding='utf-8',
                            default_filters=['decode.utf8'])

After that you may to use template engine in your web-handlers. The most convinient way is to decorate web-handler:

@aiohttp_mako.template('tmpl.html')
async def handler(request):
    return {'head': 'aiohttp_mako', 'text': 'Hello World!'}

On handler call the aiohttp_mako.template decorator will pass returned dictionary {'head': 'aiohttp_mako', 'text': 'Hello World!'} into template named "tmpl.html" for getting resulting HTML text.

If you need more complex processing (set response headers for example) you may call render_template function:

async def handler(request):
    context = {'head': 'aiohttp_mako', 'text': 'Hello World!'}
    response = aiohttp_mako.render_template('tmpl.html',
                                              request,
                                              context)
    response.headers['Content-Language'] = 'ru'
    return response

Context processors

Context processors is a way to add some variables to each template context. It calculates variables on each request.

Context processors is following last-win strategy. Therefore a context processor could rewrite variables delivered with previous one.

In order to use context processors create required processors:

async def foo_processor(request):
    return {'foo': 'bar'}

And pass them into setup():

aiohttp_mako.setup(
    app,
    context_processors=[foo_processor,
                        aiohttp_mako.request_processor],
    loader=loader)

As you can see, there is a built-in request_processor(), which adds current aiohttp.web.Request into context of templates under 'request' name.

Example

import asyncio
import aiohttp_mako
from aiohttp import web


@aiohttp_mako.template('index.html')
def func(request):
    return {'head': 'aiohttp_mako', 'text': 'Hello World!'}


async def init(loop):
    app = web.Application(loop=loop)
    lookup = aiohttp_mako.setup(app, input_encoding='utf-8',
                                output_encoding='utf-8',
                                default_filters=['decode.utf8'])
    template = """<html><body><h1>${head}</h1>${text}</body></html>"""
    lookup.put_string('index.html', template)
    app.router.add_route('GET', '/', func)

    handler = app.make_handler()
    srv = await loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler


loop = asyncio.get_event_loop()
srv, handler = loop.run_until_complete(init(loop))
try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.run_until_complete(handler.finish_connections())

Reference

aiohttp_mako.APP_KEY

The key name in aiohttp.web.Application dictionary, 'aiohttp_mako_environment' for storing mako template lookup object (mako.lookup.TemplateLookup).

Usually you don’t need to operate with application manually, left it to aiohttp_mako functions.

aiohttp_mako.get_lookup(app, app_key=APP_KEY)[source]

Get from aiohttp application instance mako.lookup.TemplateLookup object

Parameters:
Returns:

mako.lookup.TemplateLookup object which has stored in the aiohttp.web.Application

aiohttp_mako.render_template(template_name, request, context, *, app_key=APP_KEY)[source]

Return aiohttp.web.Response which contains template template_name filled with context.

Parameters:
  • template_name – name of template plus relative path.

  • requestaiohttp.web.Request object

  • context – dictionary object required to render current template

  • app_key – is an optional key for application dict, APP_KEY by default.

aiohttp_mako.setup(app, *args, app_key=APP_KEY, **kwargs)[source]

Return mako.lookup.TemplateLookup instance, which contains collections of templates.

Parameters:

by default.

License

aiohttp_mako is offered under the Apache 2 license.

Glossary

aiohttp_jinja2

jinja2 template renderer for aiohttp.web.

See https://github.com/aio-libs/aiohttp_jinja2/

jinja2

A modern and designer-friendly templating language for Python.

See http://jinja.pocoo.org/

mako

Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance.

See http://www.makotemplates.org/

Indices and tables