Pretty much what the question says. Right now I have this function using pytube:
def download(request, video_url):
url='http://www.youtube.com/watch?v='+str(video_url)
homedir = os.path.expanduser("~")
dirs = homedir + '/Downloads'
download = YouTube(url).streams.first().download(dirs)
return redirect('../../')
But this downloads the video to a directory /Downloads/
in pythonanywhere - the site that I have uploaded my project to.
How do I download the video to the user's machine? The solution doesn't have to be using the pytube package, as I just want an answer. It will be great if you tell me how to download the file as an .mp3
file too.
Thanks in advance.
When you are running a program on a remote computer (this is your server at pythonanywhere) then all operations happen at that remote computer, not the user's machine.
Therefor, when you download something on a remote computer, it will be downloaded to the remote computer (pythonanywhere).
To fulfil your requirements (download a file to the user's computer, not the server), you would probably do something like this:
YouTube....download()
.FileResponse
Every time you visit your page in your browser, your django application does roughly the following:
Usually a Django application will return an HTML page. But an HTML page is just a file, and so is your Youtube video that you are downloading. You can choose then to send back the video file instead of a web page. The user's browser will then try to open that file.
Your Django application cannot choose the download location on the user's computer. This would be a dangerous thing, if any website could just download files on your computer on any location.
However, when you send the file to the user, they can choose where to download it.
If you look at the documentation for FileResponse, you will see that you can pass an as_attachment=True
parameter.
This will make Django send a file as an "attachment", meaning that it will try to download it and not open it. This will prompt the user to choose the download location of the file.