django thread

Threads In Django REST

A thread(Threads In Django REST) is a separate flow of execution, which means we can run different parts of our code concurrently. Threads in Python are an entity within a process that can be scheduled for execution, in simple words, a thread is a computation process that is to be performed by a computer.

Let us consider an example

from .models import Student
from .serializers import StudentSerializer
from rest_framework import generics


class MyCustomMixin:
    queryset = Student.objects.all()
    serializer_class = StudentSerializer


def backgroundprocess():
    import time

    print("++++++++Process started at :", datetime.datetime.now())
    time.sleep(10)
    print("-------------Process finished on :", datetime.datetime.now())


class Thread(MyCustomMixin, generics.ListAPIView):
    import threading

    "backgroundprocess"
    t = threading.Thread(target=backgroundprocess, args=(), kwargs={})
    t.setDaemon(True)
    t.start()

Here we define our class Thread an and execute a thread function there named backgroundprocess. When the thread is executed the corresponding function “backgroundprocess” is executed. Just take a look at the sample output.

++++++++Process started at : Thu Jul 27 05:00:20 2023
-------------Process finished on: Thu Jul 27 05:00:30 2023
Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top