Created
March 8, 2011 01:33
-
-
Save sitnin/859670 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import config | |
import locale | |
import sys | |
import os | |
import tornado.database | |
import tornado.httpserver | |
import tornado.ioloop | |
import tornado.web | |
import redis | |
import threading | |
import logging | |
from uuid import uuid1 | |
from time import sleep | |
class PubSubListener(threading.Thread): | |
def __init__(self, channel, callback): | |
self.channel = channel | |
self.callback = callback | |
self.id = uuid1() | |
threading.Thread.__init__(self) | |
logging.critical("Listener created %s"%self.id) | |
def run(self): | |
r = redis.Redis() | |
r.subscribe(self.channel) | |
logging.critical("(%s) Before listen"%self.id) | |
for msg in r.listen(): | |
if msg["type"] == "message": | |
logging.critical("(%s) Message: %s"%(self.id, msg["data"])) | |
self.callback(msg["data"]) | |
r.unsubscribe(self.channel) | |
elif msg["type"] == "subscribe": | |
logging.critical("(%s) Subscribe: %s"%(self.id, msg["data"])) | |
elif msg["type"] == "unsubscribe": | |
logging.critical("(%s) Unsubscribe: %s"%(self.id, msg["data"])) | |
del self | |
class TestSub(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(self): | |
logging.critical("GET processing started") | |
PubSubListener("pubsub_test", self.on_msg).start() | |
logging.critical("After start()") | |
def on_msg(self, msg): | |
logging.critical("--- Message recieved: %s"%str(msg)) | |
self.write(str(msg)) | |
self.finish() | |
if __name__ == "__main__": | |
urls = [ | |
("/", TestSub) | |
] | |
settings = dict( | |
debug=config.debug | |
) | |
locale.setlocale(locale.LC_ALL, config.default_locale) | |
reload(sys) | |
sys.setdefaultencoding('utf-8') | |
http_server = tornado.httpserver.HTTPServer(tornado.web.Application(urls, **settings)) | |
http_server.listen(config.bind_port, config.bind_host) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment