Multiple concurrent requests in Django async views - django

From version 3.1 Django supports async views. I have a Django app running on uvicorn. I'm trying to write an async view, which can handle multiple requests to itself concurrently, but have no success.
Common examples, I've seen, include making multiple slow I/O operations from inside the view:
async def slow_io(n, result):
await asyncio.sleep(n)
return result
async def my_view(request, *args, **kwargs):
task_1 = asyncio.create_task(slow_io(3, 'Hello'))
task_2 = asyncio.create_task(slow_io(5, 'World'))
result = await task_1 + await task_2
return HttpResponse(result)
This will yield us "HelloWorld" after 5 seconds instead of 8 because requests are run concurrently.
What I want - is to concurrently handle multiple requests TO my_view. E.g. I expect this code to handle 2 simultaneous requests in 5 seconds, but it takes 10.
async def slow_io(n, result):
await asyncio.sleep(n)
return result
async def my_view(request, *args, **kwargs):
result = await slow_io(5, 'result')
return HttpResponse(result)
I run uvicorn with this command:
uvicorn --host 0.0.0.0 --port 8000 main.asgi:application --reload
Django doc says:
The main benefits are the ability to service hundreds of connections without using Python threads.
So it's possible.
What am I missing?
UPD:
It seems, my testing setup was wrong. I was opening multiple tabs in browser and refreshing them all at once. See my answer for details.

Here is a sample project on Django 3.2 with multiple async views and tests. I tested it multiple ways:
Requests from Django's test client are handled simultaneously, as expected.
Requests to different views from single client are handled simultaneously, as expected.
Requests to the same view from different clients are handled simultaneously, as expected.
What doesn't work as expected?
Requests to the same view from single client are handled by one at a time, and I didn't expect that.
There is a warning in Django doc:
You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, then Django must use a thread per request to safely emulate a synchronous environment for it.
Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”.
So it might be some sync middleware causing the problem even in the bare Django. But it also states that Django should use threads in this case and I didn't use any sync middleware, only standard ones.
My best guess, that it's related to client-server connection and not to sync or async stack. Despite Google says that browsers create new connections for each tab due to security reasons, I think:
Browser might keep the same connection for multiple tabs if the url is the same for economy reasons.
Django creates async tasks or threads per connection and not per request, as it states.
Need to check it out.

Your problem is that you write code like sync version. And you await every function result and only after this, you await next function.
You simple need use asyncio functions like gather to run all tasks asynchronously:
import asyncio
async def slow_io(n, result):
await asyncio.sleep(n)
return result
async def my_view(request, *args, **kwargs):
all_tasks_result = await asyncio.gather(slow_io(3, 'Hello '), slow_io(5, "World"))
result = "".join(all_tasks_result)
return HttpResponse(result)

Related

Django Asyncronous task running syncronously with asgiref

I'm receiving notification in my Django app via API and I should return HTTP 200 before 500 milliseconds. To achieve that I should run the related task asynchronously. I'm using asgiref library for it, everything runs ok but I think is not actually running asynchronously.
Main viev
In this view I receive the notifications. I set 2 print points to check timing in the server log.
#csrf_exempt
#api_view(('POST',))
#renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def IncomingMeliNotifications(request):
print('--------------------------- Received ---------------------')
notificacion = json.loads(request.body)
call_resource = async_to_sync(CallResource(notificacion))
print('--------------------------- Answered ---------------------')
return Response({}, template_name='assessments.html', status=status.HTTP_200_OK)
Secondary view
After receiving the notification I call the secondary view CallResource, which I expect to run asynchronously.
def CallResource(notificacion):
do things inside....
print('--------------------------- Secondary view ---------------------')
return 'ok'
Log results
When I check the log, I always get the prints in the following order:
print('--------------------------- Received ---------------------')
print('--------------------------- Secondary view ---------------------')
print('--------------------------- Answered ---------------------')
But I suppose that the Secondary viewshould be the last to print, as:
print('--------------------------- Received ---------------------')
print('--------------------------- Answered ---------------------')
print('--------------------------- Secondary view ---------------------')
What am I missing here?
I'm reading the documentation github.com/django/asgiref and as far as I can tell this should be the paradigm I'm working on:
If the outermost layer of your program is synchronous, then all async
code run through AsyncToSync will run in a per-call event loop in
arbitrary sub-threads, while all thread_sensitive code will run in the
main thread.
Any clues welcome. Thanks in advance.
async_to_sync lets a sync thread stop and wait for an async function, not run a sync function asynchronously.
Running an asynchronous task
Since you didn't mention an ASGI server, it appears you are running the sync development server python manage.py runserver.
If so, install and run Daphne (from Django) instead.
pip install daphne
daphne myproject.asgi:application
If you're using Django 3.x and above, there should already be an asgi.py file in the same directory as your wsgi.py file. See docs.djangoproject.com/en/3.2/howto/deployment/asgi/.
If you're using Django 2.x and below, upgrade to Django 3.x and above and create the asgi.py file. See How to generate asgi.py for existent project?.
You can create an async task when running an ASGI server.
# call_resource = async_to_sync(CallResource(notificacion))
loop = asyncio.get_event_loop()
task = loop.create_task(CallResource(notificacion))
An async function should be defined with async def.
# def CallResource(notificacion):
async def CallResource(notificacion):

Why can Django handle multiple requests?

According to Django is synchronous or asynchronous. Django is synchronous. However I tested a blocking view with python manage.py runserver 8100:
import time
#action(detail=False, methods=['get'])
def test(self, request):
time.sleep(5)
return {}
and triggered two requests with postman at 0s, 1s, and they returned at 5s, 6s. That seems not blocking/synchronous. Where am I wrong?
Even synchronous implementations handle usually multiple requests 'in parallel'.
They do so by using multiple processes, multiple threads or a mix of it.
Depending on the server they have a predefined (fixed) amount of processes or threads or they dynamically allocate threads or processes whenever another requests requires one.
An asynchronous server on the other hand can handle multiple requests 'in parallel' within only one thread / process.
The simple development server, that you can start with management.py runserver is using threading by default.
To best visualize this I suggest to change your code to:
import time
import os
import threading
#action(detail=False, methods=['get'])
def test(self, request):
print("START PID", os.getpid(), "TID", threading.get_native_id())
time.sleep(5)
print("STOP PID", os.getpid(), "TID", threading.get_native_id())
return {pid=os.getpid(), tid=threading.get_native_id()}
As #xyres mentioned: There is a command line option to disable threading.
Just run manage.py runserver --nothreading and try again. Now you should be able to visualize the full synchronous behavior.

Is there any simplest way to run number of python request asynchronously?

There is an API localhost:8000/api/postdatetime/, which is responsible for changing the online status of the driver. Every time a driver hits the API and if the response sent back then the driver status will be online otherwise the driver status will be offline.
Drivers need to give the response within every 10 seconds. If there is no response from the driver then he/she will be marked as offline automatically.
Currently what I am doing is getting all the logged in drivers and hitting the above-mentioned API one driver at a time.
For the simulation purpose, I populated thousands of drivers. To maintain the online-offline of thousands of drivers using my approach will leave almost many drivers offline.
The code for my approach is as described below:
online-offline.py
import requests
import random
import math
from rest_framework.authtoken.models import Token
from ** import get_logged_in_driver_ids
from ** import Driver
def post_date_time():
url = 'localhost:8000/api/postdatetime/'
while True:
# getting all logged in driver ids
logged_in_driver_ids = get_logged_in_driver_ids()
# filtering the driver who are logged in and storing their user id in the driver_query variable
driver_query = Driver.objects.only('id', 'user_id').filter(id__in=logged_in_driver_ids).values('user_id')
# storing the user id of driver in list
driver_user_ids = [driver['user_id'] for driver in driver_query]
# getting number of drivers who are supposed to hit the API
drivers_subset_count = math.ceil(len(driver_user_ids)*(random.randint(75, 85)/100))
# shuffle the driver ids list to randomize the driver id order
random.shuffle(driver_user_ids)
# getting the driver list of length drivers_subset_count
required_drivers = driver_user_ids[:drivers_subset_count]
for driver in required_drivers:
token = Token.objects.only('key', 'user_id').get(user_id=driver)
req_headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Token' + ' ' + str(token)
}
response = requests.post(url=url, headers=req_headers)
print(response.text)
if __name == '__main__':
post_date_time()
Is there any idea that I can post request the localhost:8000/api/postdatetime/ API asynchronously and can handle about 2-3000 of drivers within 10 seconds?
I am really new at implementing async codes. I have read some articles on the aiohttp library but got confused at the time of implementing it.
This online-offline.py will run for the whole time of the simulation.
Any help will be highly appreciated. Thank you :)
In case of non-local API asyncio can help you. To make requests asynchronously you have to:
use special syntax (async def, await - read here for details)
make requests non-blocking way (so you can await them)
use asyncio.gather() of similar way to make multiple requests parallely"
start event loop
While it is possible to make requests library work with asyncio using threads it's easier and better to use already asyncio-compatible library like aiohttp.
Take a look at code snippets here *: they contain examples of making multiple concurrent requests. Rewrite you code same way, it'll look like:
import asyncio
async def driver_request(driver):
# ...
# use aiohttp to make request with custom headers:
# https://docs.aiohttp.org/en/stable/client_advanced.html#custom-request-headers
async def post_date_time():
# ...
await asyncio.gather(*[
driver_request(driver)
for driver
in required_drivers
])
asyncio.run(post_date_time())
Locally you won't see any effect by default, so to test it locally you have to make localhost send response with delay to emulate real-life network delay.
* In latest Python version event loop can be run with just asyncio.run()

HTTP call after celery task have changed state

I need a scheduler for my next project, and since I'm coding using Django I went for Celery.
What I am looking for is a way for a task to tell Django when it is done, so I can update the database and use SSE to tell the user. All this can be done fairly simple with just putting all the logic into the task. But what do I do when I am planning to have several celery workers?
I found a bunch of info online to cover the single-worker-case, but not many covering the problem if you have more than one worker.
What I thought about was using http callbacks from the workers to the web-server to let it know that the task is done. Looking at celery.task.http looked promising, but didnt do what I needed.
Is the solution to use signals and hook up manual http calls? Or am I on the wrong path? Isn't this a common problem? How can this be solved more elegantly?
So, what are you mean when you tell tell to Django? Is I understand you right, django request which initiliazed a Celery task, is still alive a time when this task is finished? I that case you can check some storage ( database, memcached, etc ). and send your SSE.
Look, there is one way to do that.
1. You django view send task to Celery, after that it goes to infinite loop ( or loop with timeout 60sec?) and waits results in memcached.
Celery gets task executes, and pastes results to memcached.
Django view gets new results, exit the loop and sends your SSE.
Next variant is
Django view sends task to Celery, and returns
Celery execute tasks, after executing it makes simple HTTP requests to your django app.
Django receives a http request from Celery, parse params and send SSE to your user again
Here is some code that seems to do what I want:
In django settings:
CELERY_ANNOTATIONS = {
"*": {
"on_failure": celery_handlers.on_failure,
"on_success": celery_handlers.on_success
}
}
In the celery_handlers.py file included:
def on_failure(self, exc, task_id, *args, **kwargs):
# Use urllib or similar to poke eg; api-int.mysite.com/task_handler/TASK_ID
pass
def on_success(self, retval, task_id, *args, **kwargs):
# Use urllib or similar to poke eg; api-int.mysite.com/task_handler/TASK_ID
pass
And then you can just setup api-int to use something like:
from celery.result import AsyncResult
task_obj = AsyncResult(task_id)
# Logic to handle task_obj.result and related goes here....

Django asynchronous requests

Does Django have something similar to ASP.NET MVC's Asynchronous Controller?
I have some requests that will be handled by celery workers, but won't take a long time (a few seconds). I want the clients to get the response after the worker is done. I can have my view function wait for the task to complete, but I'm worried it will put too much burden on the webserver.
Clarification:
Here's the flow I can have today
def my_view(request):
async = my_task.delay(params)
result = async.get()
return my_response(result)
async.get() can take a few seconds - not too long so that the client can't wait for the HTTP response to get back.
This code might put unnecessary strain on the server. What ASP.NET MVC's AsynchronousController provides, is the ability to break this function in two, something similar to this:
def my_view(request):
async = my_task.delay(params)
return DelayedResponse(async, lambda result=>my_response(result))
This releases the webserver to handle other requests until the async operation is done. Once it done, it will execute the lambda expression on the result, giving back the response.
Instead of waiting for request to complete, you can return status "In progress" an then send one more request to check if status has changed. Since you're doing pure lookups, the response will be very fast and won't put much burden on your web server.
You can outsource this specific view/feature to Tornado web server which is designed for async callback. The rest of the site may continue to run on django.
Most likely the solution should be not technical, but in UI/UX area. If something takes long, it's ok to notify user about it if notification is clear.
Yes, you can do something only when the task completes. You would want to look into something called chain(). You can bind celery tasks in chain:
chain = first_function.s(set) | second_Function.s(do)
chain()
These two functions first_function and second_function will both are celery functions. The second_function is executed only when first_function finishes its execution.