Async context processors

It seems that context processors don’t have any async support.

This is pretty problematic when trying to call async-only functions inside of a “context processor” scope due to the event pool.

Any thoughts on how this should be resolved?

You are correct, the entire rendering process is sync. (There are a handful of threads here discussing this - see Is it feasible to improve streaming HTML in Django? - #2 by andrewgodwin as one example.)

If you need to call an async-only function within this process, you’ll need to use the async_to_sync method.

Yes, the rendering process needs to be async-capable for async context processors to make sense. But it would also lead to challenges in what they’d mixing async and sync rendering. Should sync rendering run only sync context processors, and async rendering only the async ones?

Another thing to be aware of is that context processors should generally avoid database queries, as I covered in this post: Django: Avoid database queries in template context processors - Adam Johnson

1 Like

@KenWhitesell Sorry if I wasn’t clear but async_to_sync doesn’t seem to work inside of context processors due to the event pool so every time you get SynchronousOnlyOperation error.

@adamchainz It also depends on how many views the project has and the expected traffic but you do bring up many excellent points in that post that I didn’t think of.

As for the rendering process, there might be a use case when async jinja is used instead of DTL but I can see how that would bring a lot of complexity just to support a third-party lib.

So I guess the current workaround would be to do any async stuff inside of the async view method and then pass along the results to the render request context.

“context processors” are a DTL-specific feature. Jinja’s equivalent is presumably async-compatible.

I’m not very familiar with jinja but at a glance, it doesn’t seem they have request context processors at all.
Unless I’ve missed something?