Django ORM database queries are server blocking or are they asynchronous?

I just want to clarify a few things.

I believe the Django server is asynchronous (because if every request from the client is blocking the server then it won't work), but I also know that Django ORM is not asynchronous. So do database queries block the server? (I mean rest requests are waiting until the request is complete?) Or maybe it works completely differently and I misunderstood it.

I am asking this because I have heard that most ORMs are blocking and therefore I cannot use them in my Twisted server to get data from the db without blocking the twisted ones.

+3


source to share


2 answers


Why does the server have to run asynchronously? Django is a WSGI application; the concurrency model depends on the server you run it on, and which can be threaded, multiprocessor, asynchronous (select loop driven), or a combination of these.



Every Django request is completely synchronous. The database query will block the query until a result is returned. It doesn't need to be aware of any other parallel requests (other than that Django handles data structures in a thread-safe manner).

+4


source


I ran into a similar problem that you seem to be facing. The django app makes a lot of service calls to render the view and it bothered me that they have to be serialized. I developed this:

https://github.com/kowalski/featdjango/

It is an application server based on a twisted network. Unlike the django-on-twisted project, it doesn't use wsgi at all. Django code runs on a thread. Their pool. The curled code runs on the main thread of the application and manages the pool. If you need to make multiple calls from Django code and can use it at the same time, you need to create a method that returns Deferred (or DeferredList). Then, from your django code, you can call it:



import threading
...

ct = threading.current_thread()
result = ct.wait_for_defer(method_to_call, *args, **kwargs)

      

This is caused by calling the * method_to_call * method with the reactor.callFromThread () method and attaching callbacks to wake up the caller's thread. A deferred result is returned, or an exception is thrown (in the case when errback () is triggered).

0


source







All Articles