With asyncio
, you can run multiple async
functions in background concurrently and asynchronously in Django view as shown below.
# "store/views.py"
import asyncio
from django.http import HttpResponse
async def test1(num):
print("Test1")
return num + 1
async def test2(num):
print("Test2")
return num + 1
async def test(request):
result1, result2 = await asyncio.gather(test1(2), test2(3))
total = result1 + result2
print(total) # 7
return HttpResponse(total) # Return 7
This is the result below:
Test1
Test2
7
[03/Nov/2022 15:12:30] "GET /store/test/ HTTP/1.1" 200 1
And, with threads, you can also run multiple functions in background concurrently in Django view as shown below.
# "store/views.py"
from threading import Thread
from django.http import HttpResponse
def test1(num, r):
print("Test1")
r[0] = num + 1
def test2(num, r):
print("Test2")
r[0] = num + 1
def call_tests_view(request):
result1 = [None] # Here
result2 = [None] # Here
thread1 = Thread(target=test1, args=(2, result1), daemon=True)
thread2 = Thread(target=test2, args=(3, result2), daemon=True)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
total = result1[0] + result2[0]
print(total) # 7
return HttpResponse(total) # Return 7
This is the result below:
Test1
Test2
7
[03/Nov/2022 15:16:45] "GET /store/test/ HTTP/1.1" 200 1