How to send mp4 as a response to react frontend.

How can i send a video mp4 file as a response for a request.

LOGS_FOLDER_PATH is received during runtime so can’t add it in media files.

@csrf_exempt
def get_video(request):
    view_logger.info("Fetching video")
    try:
        if not LOGS_FOLDER_PATH:
            view_logger.warning("LOGS FOLDER PATH not present")
            return HttpResponseNotFound("Logs folder path not set.")

        videos_path = os.path.join(LOGS_FOLDER_PATH, "videos")
        if not os.path.exists(videos_path):
            return HttpResponseNotFound("Videos folder does not exist.")

        videos_list = os.listdir(videos_path)
        if not videos_list:
            return HttpResponseNotFound("No videos found.")

        video_path = os.path.join(videos_path, videos_list[0])
        content_type = mimetypes.guess_type(video_path)
        view_logger.info(f"Video path:- {video_path}")

        return FileResponse(open(video_path, 'rb'), content_type='video/mp4')

    except Exception as error:
        view_logger.error(f"Error fetching video. Error: {error}")
        return JsonResponse({'error': 'Internal server error'}, status=500)

The best method is probably to use something like nginx or another webserver to serve your video files, and not use Python for that.

Browsers seem to require range header support to play video, and adding that to your code here isn’t totally straightforward, unfortunately. The Django have some good notes about deploying static files, but not too much about uploads.