Search code examples
pythonpython-3.xflaskyoutube-dl

How to make user download files client-side in a Flask web application?


I'm trying to build a YouTube Downloader using Flask, using the youtube-dl Python API. I've got everything working, but I have an issue with the actual download of the videos.

@app.route("/pytube/video/", methods=["POST", "GET"])
def pytube_video():
    if request.method == "POST":
        pytube_download("https://www.youtube.com/watch?v=kFZ-pW4G-s8", "313")
        return send_file("./videos/test.mp4", as_attachment=True)


@app.route("/pytube/download/", methods=["POST", "GET"])
def pytube_download(url, format_id):
    options = {
        'format': format_id,
        "outtmpl": "./videos/test.mp4",
    }

    with youtube_dl.YoutubeDL(options) as y:
        y.download([url])

This process works, but it can be very slow because I am downloading the videos locally and then sending them. Is there a way to make the user download videos in a more direct way, without downloading them first in the backend?


Solution

  • Instead of downloading the video using y.download([url]) you can extract info only like below:

    from flask import jsonify
    
    
    with youtube_dl.YoutubeDL(options) as y:
            try:
                r = y.extract_info(url, download=False)
                return jsonify(r)
            except:
                return jsonify({'error':'An error has occured'})
    

    Then you can parse the json response to extract the download link and return it to user, so the user will download directly from the video host cdn instead of consuming bandwidth from your backend.