Python implements audio streaming/file services in flask

In order to build a service in Python Flask, a simple code is given below. In this code, the audio files in the current directory are pushed each time.

from flask import Flask from flask import Response import os app = Flask(__name__) folder = './video' @app.route('/video/<file_key>') def stream_mp3(file_key): def generate(): path = os.path.join(folder, file_key) with open(path, 'rb') as video: data = video.read(1024) while data: yield data data = video.read(1024) return Response(generate(), mimetype="video") if __name__ == '__main__': = '0.0.0.0' app. The run (host, port = 8080)Copy the code

There are two video files under the file for debugging,

The code reads 1024 bytes at a time, instead of all at once, so it uses The Yield of Python. To simplify the problem, it only delivers files in the current system specified path. (There is still a lot to do in the actual work, such as logging module, video processing analysis module, etc.)

Run the code

Browser input:

The video page is displayed.