Repository navigation
Add render_async() and save_async() - #200
Merged
Merged
Conversation
Run render() and save() in a worker thread so async apps like FastAPI don't block the event loop. An optional executor caps how many run at once. Fixes #143
This was referenced Nov 23, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
Calling
render()from an async FastAPI endpoint blocks the event loop, so people end up making the endpoint sync or wrapping it themselves.render_async()andsave_async()take the same arguments and run the work in a thread throughloop.run_in_executor(). That works on 3.7, unlikeasyncio.to_thread. An optionalexecutorlets you cap how many documents are generated at once, which was the worry in the issue about running out of threads.Rendering is CPU and lxml work, so a real async rewrite wouldn't make it faster. A worker thread is what @waketzheng's anyio example does too, this just makes it a method. One template object still shouldn't be used from two tasks at the same time, the docs say so.
Fixes #143
How I tested it
New unit tests render and save three templates concurrently on a two-thread pool and check that template errors come through from the thread. All unit tests pass locally.
tests/unitCHANGES.rstupdated if users will notice the change (left for the release PR)