Streaming video files using Flask

前端 未结 1 459
独厮守ぢ
独厮守ぢ 2020-12-30 13:55

Please help me to understand one moment.

I am trying to make Flask to stream .mp4 video. I know that i can use Response(generator_function())

Bu

相关标签:
1条回答
  • 2020-12-30 14:17

    On development server you need to enable threaded=True for video stream to work correctly.

    Updated:

    @app.after_request
    def after_request(response):
        response.headers.add('Accept-Ranges', 'bytes')
        return response
    
    
    def get_chunk(byte1=None, byte2=None):
        full_path = "try2.mp4"
        file_size = os.stat(full_path).st_size
        start = 0
        length = 102400
    
        if byte1 < file_size:
            start = byte1
        if byte2:
            length = byte2 + 1 - byte1
        else:
            length = file_size - start
    
        with open(full_path, 'rb') as f:
            f.seek(start)
            chunk = f.read(length)
        return chunk, start, length, file_size
    
    
    @app.route('/video')
    def get_file():
        range_header = request.headers.get('Range', None)
        byte1, byte2 = 0, None
        if range_header:
            match = re.search(r'(\d+)-(\d*)', range_header)
            groups = match.groups()
    
            if groups[0]:
                byte1 = int(groups[0])
            if groups[1]:
                byte2 = int(groups[1])
    
        chunk, start, length, file_size = get_chunk(byte1, byte2)
        resp = Response(chunk, 206, mimetype='video/mp4',
                          content_type='video/mp4', direct_passthrough=True)
        resp.headers.add('Content-Range', 'bytes {0}-{1}/{2}'.format(start, start + length - 1, file_size))
        return resp
    
    if __name__ == '__main__':
        app.run(threaded=True)
    
    0 讨论(0)
提交回复
热议问题