Showing Progress bar in Django view during video download using youtube-dl

When a button is clicked, I make an AJAX call to 'search/'. My goal is to display the details {"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} in a progress bar on a webpage while downloading.

How can I retrieve the JSON response from the video_progress_hook function each time it's called by the 'progress_hooks' parameter in ydl_opts?

I need to capture this response in JavaScript.

Please provide assistance.

def search(request):

        file_name="" + str(uuid.uuid1()).split('-')[0] + ".mp3"
        query = request.GET.get("query")
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{'key': 'FFmpegExtractAudio',
                                'preferredcodec': 'mp3',
                                'preferredquality': '192'}],
            'outtmpl': 'media/' + file_name,
            'progress_hooks':[video_progress_hook],
            'quiet': False,
        }
        ydl = youtube_dl.YoutubeDL(ydl_opts)
        ydl.download([query])
        args = {'url_link': file_name}
        return JsonResponse(args)

    def video_progress_hook(d):
        args = {}
        if d['status'] == 'downloading':
            args = {"file_name": d['filename'], "percentage": d['_percent_str'], "speed": d['_eta_str']}
        return JsonResponse(args)
    

Answer №1

Finding a straightforward answer can be challenging at times.

The process involves storing the request in a database and sending back the corresponding ID to the user. Then, you'll have to set up a customized endpoint that tracks progress using the request ID. Your code should make periodic updates to this request at specified intervals.

One potential solution worth exploring is https://github.com/czue/celery-progress

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on obtaining JSON data in an android application through a PHP file?

I am a beginner in Android development and I have recently created a simple data fetching application. However, I am facing an issue where I am only able to retrieve the value of one variable from my PHP file, even though both variables are present in the ...

Does the onwheel event get triggered when scrolling on a trackpad?

Despite being a fundamental inquiry, the answer remains elusive to me. Due to its simplistic nature, there isn't much of an elaborate explanation available. Regrettably, I am lacking access to a laptop for testing purposes. ele.onwheel = function(e) ...

Tips for utilizing jsonSlurper() with conditional if/else statements in Groovy?

Currently, I am attempting to parse through a JSON file in order to retrieve the status associated with 'stop-emu'. def stageJson = new JsonSlurper().parseText(response?.content) stageJson.stages.each { echo(it) } //status = ???? The snippet of ...

Utilizing React to implement a timeout feature for communicating with Firebase

Currently, I am working with React and Firebase, and I need to manage the situation when a call to the database is pending for too long by displaying an error message. Below is my database call: fire.database().ref('user/').once('value&ap ...

Passing data to JavaScript (using jQuery) function

I am trying to figure out how to pass a variable to a JavaScript function when I click on a link, but I have been unable to find any information on how to do it online. Here is the script located at the top of my page: <script> $(document).ready(fu ...

adding <script> elements directly before </body> tag produces unexpected results

While following a tutorial, the instructor recommended adding <script> tags right before the </body> to enhance user experience. This way, the script will run after the entire page content is loaded. After implementing the code block as sugges ...

What is the process for triggering data-dismiss after the href has been activated?

Could someone help me with this issue? <a class='btn btn-danger' href='page.html'>Delete</a> I am trying to activate the "data-dismiss" attribute after the "href" is activated. My initial attempt was using this code: < ...

Leverage the power of Ajax combined with XMPP for real-time communication, or

I created a straightforward AJAX chat application using jQuery. The process is simple: the message is sent to a PHP file via AJAX, then the message is encoded in JSON and saved in a text file for the recipient to retrieve. The JSON format is basic, such as ...

Something is wrong with the OMDb API search using JQuery and JSON

I am currently experimenting with APIs to enhance my website. One of my projects involves using the OMDb API to search for a movie title and display its poster on my site. However, I seem to be encountering some difficulties with the code implementation. ...

What can I do to ensure that the language-picker button retains the chosen value even after being clicked and the page is refreshed?

Just diving into JQuery. I've got this jquery code for a language-picker on a multi-language website. The issue is that after the page reloads in the selected language, the language picker defaults back to the original language displayed in the div t ...

Adjusting the devicePixelRatio in Three.js to optimize rendering with CSS3DRenderer

I am looking to display a <div> element (specifically, one from the ECharts library) using the Three.js CSS3DRenderer and combine it with WebGL content. However, I have noticed that when the <div> has fixed width and height, the rendering qua ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

The functionality of Ajax with JSON is failing to work properly in Internet Explorer 11

While this ajax code functions well in Firefox, Chrome, Safari, and IE9, it encounters issues in IE 11. $.ajax({ type: req_type, url: req_url, crossDomain: true, cache: false, data: req_data, contentType: "application/json; charse ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Angular2 - Transforming SVG elements with dynamic styles using ng-style

I'm trying to create SVG lines using ng-repeat and need to adjust the translation of each line. However, I'm having trouble getting the style to apply using ng-attr-style. my-component.js: import {Component} from 'angular2/core'; @Co ...

Retrieving data from a simulated angular service and making calls accordingly

I'm struggling with writing tests for a controller method that relies on an Angular service call and needs to test the code inside the .then() function afterwards. Here's the basic concept: // Controller $scope.myMethod = function() { meth ...

What is the best way to incorporate a feature that flips all choices in react-select?

I'm working with a multi-option Select component from react-select, and I need to add a special option that will invert the selected options into unselected ones, and vice versa. When this 'Invert selection' option is chosen, I don't w ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

Fill the second dropdown menu options based on the selection made in the first dropdown menu

I need assistance with dynamically populating my second drop-down menu based on the selection made in the first drop-down. Here are the steps I've taken so far: form.php - Utilizing javascript, I have set up a function to call getgeneral.php. The se ...