Stream & Multipart

1. Generator

def gen():
    yield 1
    yield 2
    yield 3
>>> x = gen()
>>> x
<generator object gen at 0x7f06f3059c30>
>>> next(x) // python3
1
>>> next(x)
2
>>> next(x)
3
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

2. Multipart

Implement in-place updates = _multipart _response.

Multipart responses

  1. a header includes one of the multipart content types

  2. parts, separated by a _boundary _marker

HTTP/1.1 200 OK
Content-Type: multipart/x-mixed-replace; boundary=frame

--frame
Content-Type: image/jpeg

<jpeg data here>
--frame
Content-Type: image/jpeg

<jpeg data here>
...

3. Video Streaming Server = generator + multipart

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)

4. Limitation

Regular request: [1]web worker receives a request, [2]invoke handler, [3]return response, [4]the worker is free, and is available for another request.

Stream request: A worker will stay locked to the client until the client disconnects.

Last updated

Was this helpful?