Home > Back-end >  Getting empty buffer
Getting empty buffer

Time:09-08

I'm building a YouTube downloader using react for frontend and flask for backend.

To download the videos/audio from YouTube I use pytube, loading as buffer with stream.stream_to_buffer():

Here the pytube code:

from pytube import YouTube
from io import BytesIO

def get_audio_from_video(video_url: str):
    f = YouTube(video_url)
    buffer = BytesIO()
    video_selection = f.streams.get_by_itag(140)
    return video_selection.stream_to_buffer(buffer)

After I use the function in a post route that receive the url from the frontend and return the file to the frontend

from flask import Flask, request as req, jsonify
from flask_cors import CORS
from youtube_functions import get_audio_from_video

app = Flask(__name__)

CORS(app, origins="http://localhost:3000")

@app.post("/")
def send_main():
    download_encoded = req.data.decode("UTF-8")
    data = get_audio_from_video(download_encoded)
    return jsonify(data)

Finally in the frontend I receive the file returned from Flask

    const sendURL = async data => {
        const request = await fetch("http://localhost:5000", {
            method: "POST",
            body: data,
        })

        await request.arrayBuffer()
        
        .then(blob => {
                console.log(blob)
                const blobFile = window.URL.createObjectURL(new File([blob], {type: "audio/mp4"}))
                hrefButton.current.href = blobFile
            })
    }

    const saveURL = e => {
        e.preventDefault()
        let inputData = uriInput.current.value
        inputData.includes("https://youtube.com/watch?v=") ||
        inputData.includes("https://www.youtube.com/watch?v=") ||
        inputData.includes("youtube.com/watch?v=") ? sendURL(inputData) : setUrlValid(false)

But when I download the file I get this file instead the video file:

enter image description here

With this content:

enter image description here

Why is happening this and how I can fix it?

CodePudding user response:

The pytube stream_to_buffer method copies the stream into the buffer but returns None. You don't return its output, you return the buffer in a separate line.

  • Related