Skip to content

Instantly share code, notes, and snippets.

@bnadland
Created February 5, 2016 21:08
Show Gist options
  • Save bnadland/58b1dd6ef65b41e892cc to your computer and use it in GitHub Desktop.
Save bnadland/58b1dd6ef65b41e892cc to your computer and use it in GitHub Desktop.
Short example of Flask TLS and SSE
"""
Python 3.4.4
Flask==0.10.1
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.3
cffi==1.5.0
cryptography==1.2.2
idna==2.0
itsdangerous==0.24
pyOpenSSL==0.15.1
pyasn1==0.1.9
pycparser==2.14
six==1.10.0
"""
from datetime import datetime
from time import sleep
from flask import Flask, Response, render_template
app = Flask(__name__)
index_html = """
<!doctype html><html lang=en>
<head>
<title>SSL Stream</title>
</head>
<body>
<h1>hello, world</h1>
<ul id="events"></ul>
<script>
window.onload = function() {
var source = new EventSource("/stream");
source.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.innerHTML = e.data;
document.getElementById("events").appendChild(newElement);
}
}
</script>
</body>
</html>
"""
def streamer():
while True:
sleep(1)
data = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
yield 'data: {}\n\n'.format(data)
@app.route('/stream')
def stream():
return Response(streamer(), mimetype="text/event-stream")
@app.route('/')
def index():
return index_html
if __name__ == '__main__':
app.run(debug=True, threaded=True, ssl_context='adhoc')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment