Downloading file to a temporary location (e.g. in RAM), return as blob/encoded format in http-request, and delete file aftwards

Viewed 297

I am trying to download an mp3 file via the youtube-dl python library. However, I do not need it permanently stored on the file system, but rather in some temporary fast access location so i can immediately pass it on to my front end application via HTTP, and then delete it. Is there any way to create such a path?

1 Answers

The issue was solved by first creating a temporary directory using python's tempfile library. The physical directory will be cleaned up/deleted when the temporary directory is garbage collected. Then passing in the path of the directory to the youtube_dl options:

temp = tempfile.TemporaryDirectory()
temp_path = temp.name.replace("\\", "/")

ydl_opts = {
    'outtmpl': temp_path + "/%(title)s.%(ext)s",
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }]
}
Related