Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django is synchronous or asynchronous?

Django is synchronous or asynchronous?
I want to know that the Django Framework is Synchronous or Asynchronous. I have heard about the interview problems they ask about the framework you are using is synchronous or asynchronous. So I want to know the meaning of Synchronous and Asynchronous in terms of web development.

like image 505
SUMIT KUMAR Avatar asked Oct 24 '19 19:10

SUMIT KUMAR


1 Answers

Django itself is synchronous.

each HTTP request will be handled completely synchronously.

However you have extensions like django-channels ( https://github.com/django/channels ) , which are asynchronous and are intended for web sockets / etc.

This is a little oversimplified: but synchronous programming is if you write code, that handles one HTTP request from beginning to end and that is executed in a thread or in a process and if one process / one thread handles only one request at a time.

With python in particular with asyncio or with twisted one can write code such, that one process/thread can handle multiple requests. Whenever one request waits for new data on the network to be received or for a chunk of data to be sent out it can handle another request until this other requests waits for network to be ready.

Django versions < 3.0 however do not use twisted or asyncio, thus http-requests are handled only in a synchronous manner.

New web servers / web apps however don't only handle http requests, but can also use web sockets. The Django channels module is built for handling web sockets. It is implemented with asyncio, which allows to handle many web sockets with one process only. it will interact with the synchronous parts of Django via messages (e.g. redis)

Addendum: as @Sayse pointed out Django 3.0 will support asynchronous code. However: ORM operations will still be synchronous only if I understand. They will fail in an async event loop with a SynchronousOnlyOperation exception (or they had to be offloaded to a thread pool). So probably most real Django views will fail or will depend on thread pools, as one of the reasons of Django is to use an ORM for data base access.

like image 136
gelonida Avatar answered Sep 20 '22 22:09

gelonida