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())
But it does not allow to jump to specific minute while watching a video in browser.
So i am trying to use Range header. Here is how i try it:
app = Flask(__name__)
def get_chunk(byte1=None, byte2=None):
filesize = os.path.getsize('try2.mp4')
yielded = 0
yield_size = 1024 * 1024
if byte1 is not None:
if not byte2:
byte2 = filesize
yielded = byte1
filesize = byte2
with open('try2.mp4', 'rb') as f:
content = f.read()
while True:
remaining = filesize - yielded
if yielded == filesize:
break
if remaining >= yield_size:
yield content[yielded:yielded+yield_size]
yielded += yield_size
else:
yield content[yielded:yielded+remaining]
yielded += remaining
@app.route('/')
def get_file():
filesize = os.path.getsize('try2.mp4')
range_header = flask_request.headers.get('Range', None)
if range_header:
byte1, byte2 = None, None
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])
if not byte2:
byte2 = byte1 + 1024 * 1024
if byte2 > filesize:
byte2 = filesize
length = byte2 + 1 - byte1
resp = Response(
get_chunk(byte1, byte2),
status=206, mimetype='video/mp4',
content_type='video/mp4',
direct_passthrough=True
)
resp.headers.add('Content-Range',
'bytes {0}-{1}/{2}'
.format(byte1,
length,
filesize))
return resp
return Response(
get_chunk(),
status=200, mimetype='video/mp4'
)
@app.after_request
def after_request(response):
response.headers.add('Accept-Ranges', 'bytes')
return response
get_chunk yields chunks from byte1 to byte2 if this bytes are specified, and from 0 to filesize otherwise (chunk size = 1MB).
But it does not work. I see that firstly browser sends request with <200> status. And then with <206>. Please advice me how to make it working.