Opened 3 weeks ago

Last modified 3 weeks ago

#36872 closed New feature

Django's template engine cannot handle asynchronous methods — at Version 3

Reported by: Ricardo Robles Owned by:
Component: Template system Version: 6.0
Severity: Normal Keywords: Template, Async
Cc: Carlton Gibson Triage Stage: Accepted
Has patch: yes Needs documentation: yes
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description (last modified by Ricardo Robles)

Currently, the Django template is not designed to execute asynchronous methods; it is only designed to execute synchronous methods.

Here's an example of how to reproduce the error:

from django.template import engines

django_engine = engines['django']

class Example:
    def sync_method(self):
        return "Synchronous Method Result"
    async def async_method(self):
        return "Asynchronous Method Result"

html_string = """
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>sync: {{ example.sync_method }}!</h1>
    <p>async: {{ example.async_method }}</p>
</body>
</html>
"""

template = django_engine.from_string(html_string)
rendered_html = template.render({'example': Example()})

print(rendered_html)

This will return this error:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>sync: Synchronous Method Result!</h1>
    <p>async: &lt;coroutine object Example.async_method at 0x7bdeeb9aa980&gt;</p>
</body>
</html>

I had thought that a solution to this error might be to modify the resolve method of the FilterExpression class
https://github.com/django/django/blob/main/django/template/base.py#L785

If we add this:

class FilterExpression:
    ...

    def resolve(self, context, ignore_failures=False):
        if self.is_var:
            try:
                obj = self.var.resolve(context)

                # My proposal begins
                if asyncio.iscoroutine(obj):
                    obj = async_to_sync(lambda: obj)()
                # My proposal ends

            except VariableDoesNotExist:
                ...

Now it renders correctly:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>sync: Synchronous Method Result!</h1>
    <p>async: Asynchronous Method Result</p>
</body>
</html>

I use Django ASGI a lot at work, and there are many features like this that would be very useful. I look forward to your feedback.

Change History (3)

comment:1 by ar3ph, 3 weeks ago

in reply to:  1 comment:2 by Ricardo Robles, 3 weeks ago

Replying to Zachary W:

Could be related. There is an async_to_sync function in asgiref: https://github.com/django/asgiref/blob/2b28409ab83b3e4cf6fed9019403b71f8d7d1c51/asgiref/sync.py#L585

You're correct, the most elegant and simple way to do it would be:

    def resolve(self, context, ignore_failures=False):
        if self.is_var:
            try:
                obj = self.var.resolve(context)
                if asyncio.iscoroutine(obj):
                    obj = async_to_sync(lambda: obj)()
                ...

comment:3 by Ricardo Robles, 3 weeks ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top