Async Support

Starting with version 2.9, Jinja2 also supports the Python async andawait constructs. As far as template designers go this feature isentirely opaque to them however as a developer you should be aware of howit’s implemented as it influences what type of APIs you can safely exposeto the template environment.

First you need to be aware that by default async support is disabled asenabling it will generate different template code behind the scenes whichpasses everything through the asyncio event loop. This is important tounderstand because it has some impact to what you are doing:

  • template rendering will require an event loop to be set for thecurrent thread (asyncio.get_event_loop needs to return one)

  • all template generation code internally runs async generators whichmeans that you will pay a performance penalty even if the non syncmethods are used!

  • The sync methods are based on async methods if the async mode isenabled which means that render for instance will internally invokerender_async and run it as part of the current event loop until theexecution finished.

Awaitable objects can be returned from functions in templates and anyfunction call in a template will automatically await the result. Thismeans that you can let provide a method that asynchronously loads datafrom a database if you so desire and from the template designer’s point ofview this is just another function they can call. This means that theawait you would normally issue in Python is implied. However thisonly applies to function calls. If an attribute for instance would be anavaitable object then this would not result in the expected behavior.

Likewise iterations with a for loop support async iterators.