Last active
August 29, 2015 14:23
-
-
Save bj0/89ceb572dd26a883c5f2 to your computer and use it in GitHub Desktop.
SeverSentEvent example with bottle + gevent/eventlet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from gevent import monkey, sleep, getcurrent, spawn | |
# from gevent.queue import Queue | |
# monkey.patch_all() | |
from eventlet import monkey_patch, sleep, spawn | |
from eventlet.queue import Queue | |
monkey_patch() | |
import re | |
import subprocess as sp | |
import time | |
import bottle | |
from bottle import request, Bottle, abort, run, response | |
bottle.debug(True) | |
app = Bottle() | |
clients = [] | |
def gen(): | |
q = Queue() | |
_id = 1#id(getcurrent()) | |
try: | |
clients.append(q) | |
yield 'retry: 10000\n\n' | |
for i in iter(q.get,'sentinal'): | |
print('sending') | |
yield u'data: {}\n\n'.format(i) | |
except Exception as ex: | |
print('except:',ex) | |
finally: | |
print('disconnected') | |
clients.remove(q) | |
# this doesn't get called | |
@app.route('/events') | |
def events(): | |
# disable buffering for this response | |
request.environ['eventlet.minimum_write_chunk_size'] = 1 | |
response.content_type = 'text/event-stream' | |
response.cache_control = 'no-cache' | |
return gen() | |
@app.get('/') | |
def root(): | |
return ''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> | |
</script> | |
<script> | |
$(document).ready(function() { | |
console.log('in'); | |
var es = new EventSource("/events"); | |
es.onmessage = function (e) { | |
//var data = JSON.parse(e.data) | |
$("#log").html(e.data); | |
}; | |
es.onerror = function(e) { | |
$("#log").html($("#log").html() | |
+ "<p>Error: " + e.name + ", msg: " + e.message + "</p>"); | |
}; | |
}); | |
</script> | |
</head> | |
<body> | |
<div id="log" style="font-family: courier; font-size: 0.75em;">hi</div> | |
</body> | |
</html> | |
''' | |
def serve(): | |
print('serve') | |
while True: | |
sleep(3) | |
i = sp.check_output('top -n1 -b |head -12', shell=True).replace(b'\n',b'<br/>') | |
for q in clients: | |
# print('put {}'.format(i)) | |
print('put') | |
q.put(i) | |
spawn(serve) | |
run(app, host='localhost', port=8888, server='eventlet') | |
# run(app, host='localhost', port=8888, server='gevent') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment