3

Since django 3.0 supports async I wonder what happens on database querying. I don't see any updates in the official documentation which I'm sure that syntax like this:

b5.name = 'New name'
b5.save()

Will totally block the current thread, which event loop is running it. And If the database is returning the response for 20 seconds, no other request would be processed during that time which is nasty.

Another thing that makes me wonder: async uses only 1 thread (if we don't await things in thread-executor at least). Here's the fact: an atomic (database) request is bound to the connection of the database, which is bound to the thread-local variable. Which means all the requests would run in the single thread = all of them would have the same transaction.

deathangel908
  • 8,601
  • 8
  • 47
  • 81
  • Normally requests are processed by different threads, hence it is already, to the best of my knowledge, asynchronous *per request*. – Willem Van Onsem Dec 20 '19 at 08:46
  • What's the point of [asgi](https://asgi.readthedocs.io/en/latest/) then? How would it make different from django 2.0? I still can use await inside my views if I use django 2.0 with py 3.5+ – deathangel908 Dec 20 '19 at 08:48
  • 5
    Django 3.0 has, quote, "developing support for async Python", it's far from ready. See https://docs.djangoproject.com/en/3.0/topics/async/ – AKX Dec 20 '19 at 08:49

2 Answers2

1

As Willem says, it is asynchronous by request. The difference of asgi, is that in a single request it can be resolved faster, since also within the request it is asynchronous. For example when consulting on the BD or consulting a resource on the web. It is true that Django 3.0 still lacks to be totally asynchronous, for you to use asynchronous benefits you have to make use of the asgi library, with the methods: sync_to_async and async_to_sync. Review this documentation so you have an idea of how it works: https://channels.readthedocs.io/en/latest/topics/databases.html

In the same way, I share this league that explains very well all the differences, of parallelism, asynchronous, threads. etc. https://fastapi.tiangolo.com/async/#asynchronous-code

felocru
  • 23
  • 4
0

Finally, since 3 years Django 4.2 released on 3 May with async support for querring models

async def make_book(*args, **kwargs):
    book = Book(...)
    await book.asave(using="secondary")
deathangel908
  • 8,601
  • 8
  • 47
  • 81