Project help on async method in django

Hi everyone.

I have add_event method that calls _post method as async using sync_to_async in Django. but when I test the method inside of Django shell, it does not even run my async _post function and returns coroutine object instead.

Here is my method:

    def add_event(cls, data):
        async_post_request = sync_to_async(
            cls._post, thread_sensitive=True
        response = async_post_request(
        return response

Screenshot of Django shell:

It’s my understanding that you can’t run async functions directly in the Python shell - at least not without creating the event loop and running your code in that event loop.

However, you can install IPython and configure Django to use IPython, at which point you should have the Autoawait feature available.

(Note - I haven’t tried this - this is just what I’ve found from the docs.)

1 Like

If cls._post is an async function, then you need to use async_to_sync.

1 Like

No cls._post is sync.

Response here will be a coroutine. It would need to be awaited. (Hence the error I suppose.)

As per you she’ll output that’s the case, I see.

This usage doesn’t really make sense. :thinking:

1 Like

I use this example from django doc

from asgiref.sync import sync_to_async

def _get_blog(pk):
    return Blog.objects.select_related('author').get(pk=pk)

get_blog = sync_to_async(_get_blog, thread_sensitive=True)

there is no await here.

But that’s a function based view, not a class method…

1 Like