Skip to content

Instantly share code, notes, and snippets.

@Chris2048
Last active October 10, 2015 12:08
Show Gist options
  • Save Chris2048/3687523 to your computer and use it in GitHub Desktop.
Save Chris2048/3687523 to your computer and use it in GitHub Desktop.
example use of sse
#!/bin/python2.7
# -`*- coding: utf-8 -*-
from gevent import monkey
monkey.patch_all()
import flask
app = flask.Flask(__name__)
app.debug = True
app.secret_key = 'asdf'
import redis
red = redis.Redis()
from sse import PeriodicStream, RedisSseStream
import random
def numGen():
prev = 50
while True:
vals = [prev]
vals.append(prev + random.randrange(-10, 10))
vals.append(prev + random.randrange(-20, 20))
vals.append(prev + random.randrange(-30, 30))
vals.append(prev + random.randrange(-40, 40))
prev = vals[-1]
if prev > 100:
prev = 100
if prev < 0:
prev = 0
for i in vals:
yield i
numgen = numGen()
numgen2 = numGen()
def ping(subscriber, freq):
if (subscriber.counter / freq) % 2 == 0:
subscriber.sse.add_message("PING", event='ping')
else:
subscriber.sse.add_message("PONG", event='ping')
def foo(subscriber, freq):
subscriber.sse.add_message(numgen2.next(), event='graph')
app.add_url_rule('/stream',
view_func=PeriodicStream.as_view(str('PeriodicStream'),
{'foo': (1, foo), 'ping': (10, ping)}))
def data_points(subscriber):
subscriber.sse.add_message(red.get('nextval'), event='graph')
app.add_url_rule('/stream2',
view_func=RedisSseStream.as_view(str('RedisSseStream'),
{'graphvals': data_points},
red.pubsub()))
@app.route('/graph')
def visit():
nextval = numgen.next()
red.set('nextval', nextval)
red.publish('stream', 'graphvals')
return '<!doctype html><head><body>%d</body></html>' % nextval
@app.route('/')
def home():
return """
<!doctype html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/flot/0.7/jquery.flot.min.js">
</script>
<script>
jQuery( function($) {
var data = [];
function get_data(yval) {
while (data.length != 300) {
data.push(0);
}
data = data.slice(1);
data.push(yval);
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]]); }
return res;
}
var data2 = [];
function get_data2(yval) {
while (data2.length != 300) {
data2.push(0);
}
data2 = data2.slice(1);
data2.push(yval);
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data2.length; ++i) {
res.push([i, data2[i]]); }
return res;
}
var options = {
series: { shadowSize: 0 },
lines: { show: true, fill: true },
yaxis: { show: false, min: 0, max: 100 },
xaxis: { show: false }
};
d1 = get_data2(0);
d2 = get_data(0);
var plot = $.plot( $("#gplot"),
[ { data: d1 }, { data: d2 } ], options
);
function update_gplot(yval) {
d2 = get_data(yval);
plot.setData([ { data: d1 }, { data: d2 } ]);
plot.draw();
}
function update_gplot2(yval) {
d1 = get_data2(yval);
plot.setData([ { data: d1 }, { data: d2 } ]);
plot.draw();
}
var source = new EventSource('/stream');
source.addEventListener(
'graph', function(e) {
update_gplot(e.data);
}, false
);
source.addEventListener(
'ping', function(e) {
$('#data').text(e.data);
}, false
);
var source2 = new EventSource('/stream2');
source2.addEventListener(
'graph', function(e) {
update_gplot2(e.data);
}, false
);
} );
</script>
</head>
<body>
<div id="data">PING</div>
<div id="gplot" style="width:600px;height:300px;"></div>
</body>
</html>
"""
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment