Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interface blocking and non-blocking code with asyncio

I'm trying to use a coroutine function outside of the event loop. (In this case, I want to call a function in Django that could also be used inside the event loop too)

There doesn't seem to be a way to do this without making the calling function a coroutine.

I realize that Django is built to be blocking and a therefore incompatible with asyncio. Though I think that this question might help people who are making the transition or using legacy code.

For that matter, it might help to understand async programming and why it doesn't work with blocking code.

like image 269
leech Avatar asked May 27 '14 20:05

leech


1 Answers

After a lot of research I think these solutions could be helpful:

  1. Update your legacy code to use asyncio:

    Yes i know that it can be hard and painful, but it might be the sanest choice. If you are wanting to use Django like I was... Well, you've got a lot of work to do to make Django async'd. I'm not sure it is possible, but I found at least one attempt: https://github.com/aaugustin/django-c10k-demo (Though, in a youtube video the author explained all the shortcomings of this).

  2. use asyncio.async or asyncio.Task:

    These items will enable you to run something async inside of blocking code, but the downfall here is that you will not be able to wait for them to finish without doing something ugly like a while loop that checks if the future has completed... ugh, but if you don't need the result, that might work for you.

like image 65
leech Avatar answered Jan 03 '23 02:01

leech