Streaming MOVIE Python flask

后端 未结 2 1816
梦如初夏
梦如初夏 2021-01-16 05:15

I have a small project about streaming movie(720p). in Python Flask, Can anyone give me a example how to stream a video from a local disk in python flask. so its played on t

相关标签:
2条回答
  • 2021-01-16 05:32

    There is an excellent article on this subject, Video Streaming with Flask, written by Miguel Grinberg on his blog.

    As he says and explains it very well, streaming with Flask is as simple as that:

    app.py

    #!/usr/bin/env python
    from flask import Flask, render_template, Response
    from camera import Camera
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    def gen(camera):
        while True:
            frame = camera.get_frame()
            yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
    
    @app.route('/video_feed')
    def video_feed():
        return Response(gen(Camera()),mimetype='multipart/x-mixed-replace; boundary=frame')
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    index.html:

    <html>
      <head>
        <title>Video Streaming Demonstration</title>
      </head>
      <body>
        <h1>Video Streaming Demonstration</h1>
        <img src="{{ url_for('video_feed') }}">
      </body>
    </html>
    

    All the details are in the article.

    From there...

    In your case the work is considerably simplified :

    to stream pre-recorded video you can just serve the video file as a regular file. You can encode it as mp4 with ffmpeg, for example, or if you want something more sophisticated you can encode a multi-resolution HLS stream. Either way you just need to serve the static files, you don't need Flask for that.

    Source : Miguel's Blog

    0 讨论(0)
  • 2021-01-16 05:36

    You might have come across manual solutions but Flask already has a helper function for you to stream media files with ease.

    You need to use the send_from_directory method from helpers.py https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_from_directory

    you can use it like this:

    @app.route("/movies", methods=["GET"])
    def get_movie():
        return send_from_directory(
                    app.config["UPLOAD_FOLDER"],
                    "your_movie.png",
                    conditional=True,
                )
    
    0 讨论(0)
提交回复
热议问题