Skip to content

Instantly share code, notes, and snippets.

@cablehead
Created October 30, 2012 19:23
Show Gist options
  • Select an option

  • Save cablehead/3982405 to your computer and use it in GitHub Desktop.

Select an option

Save cablehead/3982405 to your computer and use it in GitHub Desktop.
import os
import time
import uuid
import simplejson
import gevent
import gevent.queue
from gevent import monkey; monkey.patch_all()
from bottle import route, run, view, request, response
from simperium import core
appname = 'xxx'
entity = 'xxx'
admin_key = 'xxx'
class Monitor(object):
def __init__(self):
self.queue = gevent.queue.Queue()
self.last = time.time()
monitors = {}
@route('/')
@view('index')
def index():
return {}
@route('/api')
def api():
_id = request.get_cookie('_id', uuid.uuid4().hex)
response.set_cookie('_id', _id)
monitor = monitors.setdefault(_id, Monitor())
monitor.last = time.time()
try:
change = monitor.queue.get(timeout=10)
except gevent.queue.Empty:
return simplejson.dumps({'heart beat': 'all is quiet'})
return simplejson.dumps(change)
def listener():
b = core.Bucket(appname, admin_key, entity)
cv = None
while True:
for change in b.all(cv):
keys = monitors.keys()
for _id in keys:
if (time.time() - monitors[_id].last) > 5*60:
del monitors[_id]
else:
monitors[_id].queue.put(change)
cv = change['cv']
gevent.spawn(listener)
port = int(os.environ.get('PORT', 5000))
run(host='0.0.0.0', port=port, server='gevent')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment