How to run function in background in Django view

Question:

I have Django project with one view. When I refresh page I want to call some function which is very complicated and take same time to execute. How and what is the best way to do it in backround?

import time
import psycopg2
from django.http import HttpResponse

def long_time_function(sec):
    time.sleep(sec)
    print('DONE')

def index(request):
   
    long_time_function(100)

    return HttpResponse('INDEX page')

There is some built in solutions to do that or I need to run this function with thread or multiprocessing and set Deamon = True ?

Asked By: Dmiich

||

Answers:

Maybe you can take a look at the async support. async

Answered By: saro

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
Answered By: Kai – Kazuya Ito