Ask Your Question
2

How can I upload a video in the background using a serializer in my API view and receive a response without waiting for the upload to complete?

asked 2021-06-29 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-08-31 09:00:00 +0000

lalupa gravatar image

One way to upload a video in the background and receive a response without waiting for the upload to complete is to use asynchronous programming. You can use the celery library along with a task queue to handle the video uploads asynchronously.

First, you need to create a Celery task to handle the video upload. This task should take in the necessary data, such as the file path and any other metadata, and perform the upload asynchronously. Once the upload is complete, the task can return a response to the API view indicating that the upload was successful.

Here is an example of what the Celery task might look like:

from celery import shared_task
from django.core.files.storage import default_storage

@shared_task
def upload_video(file_path, metadata):
    # Perform the video upload asynchronously
    with open(file_path, 'rb') as f:
        default_storage.save(metadata['filename'], f)

    return {'status': 'success'}

Then, in your API view, you can call this task using the delay() method, which queues the task to be executed asynchronously:

class VideoUploadView(APIView):
    serializer_class = VideoSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            # Get the file path and metadata from the serializer
            file_path = serializer.validated_data['file_path']
            metadata = serializer.validated_data['metadata']

            # Queue the upload task to be executed asynchronously
            upload_video.delay(file_path, metadata)

            # Return a response indicating that the upload was successful
            return Response({'status': 'success'})

        # If the serializer is not valid, return an error response
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

In this example, the view simply queues the upload task and returns a response indicating that the upload was successful. The actual upload process takes place asynchronously in the Celery task, allowing the view to return quickly without waiting for the upload to complete.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-29 11:00:00 +0000

Seen: 7 times

Last updated: Aug 31 '21