How to make Django Rest Apis Async

560 views
Skip to first unread message

Mrinal Kamboj

unread,
Apr 20, 2020, 5:39:02 PM4/20/20
to django...@googlegroups.com
Hello Everyone,

Following is my Django application configuration:

django = 2.2.11
djangorestframework = 3.9.2

Python = 3.8.2

I am exposing a set of rest apis for react js frontend, which connects to Postgres using a layered architecture views (controller) - services - data_layer. In data layer I fetch the data using Connection.Cursor, then transform the data fetched using cursor.fetchall.

By default the rest apis are synchronous apis, I am trying to find a way to make them Async, so that system scalability can be increased, otherwise every call will block the main thread.

I have tried the following options:

1. Using asyncio library, but I am unable to make the complete call chain Async. I generally get an error that expected return was Response / HttpResponse, but the method is returning Co-routine. I can find examples which contains running simple methods as async, but there's isn't an example of Django Rest API

2. Tried the following link, https://hackernoon.com/how-to-run-asynchronous-web-requests-in-parallel-with-python-3-5-without-aiohttp-264dc0f8546, which use the Threadpool executor to segregate every call on a thread in the controller itself, though the challenge is where to make the Asyncio call in the Main method as shown in the link, since these APIs are externally invoked.

3. Can aiohttp help, not sure, but if anyone has an example otherwise I have to resort to service broker design using an intermediary like Redis which in my view is unrequired complexity.

Any help / link on the topic would be appreciated.

Thanks,

Mrinal

Aldian Fazrihady

unread,
Apr 20, 2020, 11:29:31 PM4/20/20
to django...@googlegroups.com
Hi Mrinal,

My DRF views usually send asynchronous tasks to celery or channel workers.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPSS-O%2Bm2vOS6D7c_fNFNDccmxBVMJqQZ58bNUtrjTd42Jdf%3Dw%40mail.gmail.com.


--
Regards,

Mrinal Kamboj

unread,
Apr 21, 2020, 1:45:58 AM4/21/20
to django...@googlegroups.com
Hi Aldian,

Thanks for the reply. I am pretty new to Django, using Celery seems to be a service broker design, do you have some reference links / samples available, which can help me guide through the process

Thanks,

Mrinal

Reply all
Reply to author
Forward
0 new messages