Play a downloaded video with flask

RandomGuyqwert picture RandomGuyqwert · Dec 12, 2015 · Viewed 9.2k times · Source

I have a simple flask server. I downloaded, using pafy, a video from a youtube link provided by the user.

@app.route('/')
def download():
    return render_template('basic.html')

The basic.html template has a form that submits an action to download:

<form action="download_vid" method="post">
Link: <input type="text" name="download_path"><br>
<input type="submit" value="Submit">
</form>

I have another end point, /download_vid that looks like this.

@app.route('/download_vid', methods=['POST'])
def download_vid():
    url = request.form['download_path']
    v = pafy.new(url)
    s = v.allstreams[len(v.allstreams)-1]
    filename = s.download("static/test.mp4")
    return redirect(url_for('done'))

The desired link is indeed downloaded as a .mp4 file in my static folder. I can watch it and I can also use it as a source for a tag in an HTML file, if I open it locally.

@app.route('/done')
def done():
    return app.send_static_file('test.mp4')

From what I understand, 'send_static_file' serves files from the static directory. However, I get a 404 error when I run the server, even though the video is clearly there.

I have also tried a different version for done():

@app.route('/done')
def done():
    return return render_template('vid.html')

Here, vid.html resides in templates and has a hard coded path to static/test.mp4. It is loaded after the download is complete. I do not have a 404 error in this case, but the tag don't do anything, it's just gray. If I open vid.html locally (double click on it), it works, it shows the video.

Can you please help me understand what is going on?

What I want to achieve is this:

  1. Take an input from the user [ Done ]
  2. Use that input to download a video [ Done ]
  3. Serve that video back to the user [ ??? ]

Answer

masnun picture masnun · Dec 12, 2015

I think you have something going on with file paths or file permissions.

  • Is the video being downloaded into static directory?
  • Is the static directory in the same directory, along with your main.py file?
  • Does your flask app have permissions to read the file?

I think the reason your file did not load in html template is because you referenced it as static/test.mp4 from an url - /done which translates the video path to be /done/static/test.mp4.

Instead of trying to push the file using Flask, you can redirect to the actual media file.

@app.route('/done')
def done():
    return redirect('/static/test.mp4')