Skip to content

Instantly share code, notes, and snippets.

@ncode
Forked from gleicon/tinymq.py
Created February 7, 2012 03:40
Show Gist options
  • Save ncode/1757013 to your computer and use it in GitHub Desktop.
Save ncode/1757013 to your computer and use it in GitHub Desktop.
tiny gevent based restmq
from bottle import route, run, debug, abort, request, ServerAdapter, response, get, post
import redis
import json
import gevent
from gevent import monkey
monkey.patch_all()
QUEUESET = 'QUEUESET'
UUID_SUFFIX = ':UUID'
QUEUE_SUFFIX = ':queue'
redis_cli = redis.Redis()
@route('/')
def all_queues():
qs = redis_cli.smembers(QUEUESET)
if qs is None: abort(404, "No queues created")
l = ["/q/%s" % q for q in qs]
return json.dumps(l)
@route('/c/:q')
def queue(q = None):
if q is None: abort(404, "No queue given")
q = q + QUEUE_SUFFIX
yield q
while(True):
b = redis_cli.rpop(q)
if b is not None: v = redis_cli.get(b)
print v
yield v
yield "oie"
gevent.sleep(5)
@get('/q/:q')
def queue(q = None):
if q is None: abort(404, "No queue given")
q = q + QUEUE_SUFFIX
if "soft" in request.GET.keys(): b = redis_cli.lindex(q, -1)
else: b = redis_cli.rpop(q)
if b is None: abort(404, "Empty queue")
v = redis_cli.get(b)
if v is None: abort(404, "Empty value/no val")
return json.dumps({"value": v, "key": b})
@post('/q/:q')
def queue(q = None):
if q is None: abort(404, "No queue given")
qkey = q + QUEUE_SUFFIX
value = request.POST['value']
if value is None: abort(401, "No value given")
uuid = redis_cli.incr(q + UUID_SUFFIX)
redis_cli.sadd(QUEUESET, q)
lkey = "%s:%d" % (q, uuid)
redis_cli.set(lkey, value)
redis_cli.lpush(qkey, lkey)
return json.dumps({"ok": lkey})
@route('/stats/:queuename')
def stats(q):
pass
# get and post
#class GEventServerAdapter(ServerAdapter):
# def run(self, handler):
# from gevent.wsgi import WSGIServer
# WSGIServer((self.host, self.port), handler).serve_forever()
#debug(True)
#run(host='localhost', port=8080, server=GEventServerAdapter)
run(host='localhost', port=8080, server='gevent')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment