Streaming with Flask

Multipart the shit to your browser



Dennis "@the_metalgamer" Fink

28 October 2014

at "Spark-Up: Be prepared!" by C3L

Ever wanted to stream your webcam to the browser?

Maybe IP-Cam?

THEY'RE ARE FREAKING INSECURE!

Ok, we need to code it by ourselve?

So what to use?

Flash? Javascript?

Ever heard of MIME and multipart/mixed ?

Generator functions

Example

def generator():
    yield 1
    yield 2
    yield 3

Example

>>> x = generator()
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Multipart responses

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>
...

Flask Example

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):
    for frame in camera.read():
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' +
               frame +
               b'\r\ņ')

Flask Example

@app.route('/video_feed')
def video_feed():
    return Response(gen(Camera()),
                    mimetype=
                    'multipart/x-mixed-replace; boundary=frame')

Template

{% block body %}
<div>
  <h1>Realtime Facedetection Demonstration</h1>
  <img src="{{ url_for('video_feed') }}">
</div>
{% endblock %}

LIVE DEMO

Conclusion

SpaceForward
Left, Down, Page DownNext slide
Right, Up, Page UpPrevious slide
POpen presenter console
HToggle this help