def open(self): # FIXME: make chat_channel dynamic self.chat_channel = "chat" self.chat_userset = chat_userset_key(self.chat_channel) self.from_user = self.get_current_user()['name'] host, port = options.redis.split(":") self.sub_client = Client() self.sub_client.connect(host, int(port)) logging.debug("Opened subscribe connection to redis for user=%s", self.from_user) # first add entered user in user_set, then subscribe to notifications def sadd_finished(resp): self.sub_client.subscribe(self.chat_channel, callback=self.on_redis_message) self.sub_client.sadd(self.chat_userset, self.from_user, callback=sadd_finished) logging.info("%s joined the chat", self.from_user) ChatSocketHandler.send_message(self.chat_channel, self.from_user, "joined the chat", system=True)
async def get_grouped_count(group_type, content_id): """ Sends document id and group type to redis and returns page view count as response. """ group_value = get_group_value(group_type) if group_value is None: return 0 redis = Client() redis.connect(config.HOST, config.PORT) response = await gen.Task(redis.zcard, "{0}:{1}".format(group_value, content_id)) return response
def test_subscribe(self): """ Tests a subscription message """ # conn = redis.Redis() conn = Client() conn.connect() def publish_message(): conn.publish("foo", "bar") self.io_loop.add_timeout(time.time() + 0.5, publish_message) response = self.fetch("/") # blocks self.assertEqual(response.code, 200)
def __init__(self): options = {'disconnect_delay': 5, 'jsessionid': False, 'sockjs_url': 'https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.min.js'} self.WaitRouter = SockJSRouter(WaitingRoomConnection, '/sockjs/wait', options) self.GameRouter = SockJSRouter(GameConnection, '/sockjs/game', options) self.SessionRouter = SockJSRouter(SessionConnection, '/sockjs/session', options) GameConnection.ready = 0 GameConnection.size = 2 urls = [ (r'/', handlers.MainHandler), (r'/session', handlers.SessionHandler), (r'/about', RegisterHandler), (r'/quiz/user/([a-zA-Z0-9])*', handlers.QuizHandler), (r'/instructionsemployer([^/]*)', handlers.InstructionsHandler), (r'/instructionsemployee([^/]*)', handlers.Instructions2Handler), (r'/tutorial1/user/([a-zA-Z0-9])*', handlers.TutorialHandler), (r'/tutorial2/user/([a-zA-Z0-9])*', handlers.Tutorial2Handler), (r'/welcome([^/]*)', handlers.WelcomeHandler), (r'/payment([^/]*)', handlers.PaymentHandler), (r'/game/user/([a-zA-Z0-9])*', handlers.GameHandler), (r'/api/player/register([^/]*)', handlers.PlayerCreateHandler), (r'/api/player/(.*)', handlers.PlayerHandler), (r'/api/credential', handlers.CredentialHandler), (r'/experimenter/config/sync/activate/([a-zA-Z0-9]+$)', handlers.SyncExperimentLaunchHandler), (r'/admin/user', handlers.UserHandler), (r'/admin', AdminHandler) ] + self.WaitRouter.urls + self.GameRouter.urls + self.SessionRouter.urls settings = { "debug": True, "template_path": os.path.join(os.path.dirname(__file__), "templates"), "static_path": os.path.join(os.path.dirname(__file__), "static"), "cookie_secret": "__TODO:_GENERATE_RANDOM_VALUE_HERE__" } self.redis_cmd = redis.Redis(db=0, \ password='******', \ unix_socket_path='/tmp/redis.sock') self.redis_pub = Client() self.redis_pub.connect_usocket('/tmp/redis.sock', callback=self.auth) tornado.web.Application.__init__(self, urls, **settings)
class ChatSocketHandler(UserMixin, tornado.websocket.WebSocketHandler): cache_size = 30 commands_client = Client() pub_client = Client() def open(self): # FIXME: make chat_channel dynamic self.chat_channel = "chat" self.chat_userset = chat_userset_key(self.chat_channel) self.from_user = self.get_current_user()['name'] host, port = options.redis.split(":") self.sub_client = Client() self.sub_client.connect(host, int(port)) logging.debug("Opened subscribe connection to redis for user=%s", self.from_user) # first add entered user in user_set, then subscribe to notifications def sadd_finished(resp): self.sub_client.subscribe(self.chat_channel, callback=self.on_redis_message) self.sub_client.sadd(self.chat_userset, self.from_user, callback=sadd_finished) logging.info("%s joined the chat", self.from_user) ChatSocketHandler.send_message(self.chat_channel, self.from_user, "joined the chat", system=True) def on_redis_message(self, msg): msg_type, msg_channel, msg = msg logging.debug("Got message from Redis: type=%s, channel=%s, msg=%s", msg_type, msg_channel, msg) if msg_type == b"message": # write message back to websocket self.write_message(json.loads(msg.decode())) def on_close(self): logging.info("%s left the chat", self.from_user) self.sub_client.srem(self.chat_userset, self.from_user) ChatSocketHandler.send_message(self.chat_channel, self.from_user, "left the chat", system=True) def on_message(self, message): logging.info("got message %r", message) ChatSocketHandler.send_message(self.chat_channel, self.from_user, message) @classmethod def update_lastmessages(cls, chat_channel, chat): cls.pub_client.lpush(chat_lastmessages_key(chat_channel), json.dumps(chat)) cls.pub_client.ltrim(chat_lastmessages_key(chat_channel), 0, cls.cache_size) @classmethod def last_messages(cls, chat_channel, callback): """get last messages""" if not cls.commands_client.is_connected(): host, port = options.redis.split(":") cls.commands_client.connect(host, int(port)) logging.debug("Opened commands connection to redis") def transform(response): json_resp = [json.loads(x.decode("utf8")) for x in response] callback(json_resp[::-1]) cls.commands_client.lrange(chat_lastmessages_key(chat_channel), 0, cls.cache_size, callback=transform) @classmethod def current_users(cls, chat_channel, callback): """get last messages""" if not cls.commands_client.is_connected(): host, port = options.redis.split(":") cls.commands_client.connect(host, int(port)) logging.debug("Opened commands connection to redis") def transform(response): json_resp = [x.decode("utf8") for x in response] callback(json_resp) cls.commands_client.smembers(chat_userset_key(chat_channel), callback=transform) @classmethod def send_message(cls, chat_channel, from_user, body, system=False): if not cls.pub_client.is_connected(): host, port = options.redis.split(":") cls.pub_client.connect(host, int(port)) logging.debug("Opened publish connection to redis") if not system: body = message_beautify(body) chat_msg = { "id": str(uuid.uuid4()), "from": from_user, "when": datetime.now().strftime("%Y-%m-%d %H:%M"), "body": body, "system": system, } cls.update_lastmessages(chat_channel, chat_msg) logging.debug("Broadcasting message %s", chat_msg) cls.pub_client.publish(chat_channel, json.dumps(chat_msg))
def get(self): self.client = Client() self.client.connect() self.client.subscribe("foo", callback=self.on_receive)
import logging import tornado.ioloop from tornado import gen from toredis import Client @gen.engine def test(): # Authenticate first status = yield gen.Task(redis.auth, '12345') assert status == 'OK' # Select database status = yield gen.Task(redis.select, '0') assert status == 'OK' print('Success') io_loop.stop() if __name__ == "__main__": logging.basicConfig() io_loop = tornado.ioloop.IOLoop.instance() redis = Client() redis.connect('localhost', callback=test) io_loop.start()
# -*- coding: utf-8 -*- from tornado import httpclient from toredis import Client redis_client = Client() redis_client.connect('localhost') http_client = httpclient.AsyncHTTPClient()
def has_connected(application, io_loop): def handle(*args, **kw): pass return handle application = tornado.web.Application([ (r"/", MainHandler), (r"/report", GetReportHandler), (r"/healthcheck", HealthCheckHandler), ], static_path=root_path, template_path=root_path) redis_host = settings.REDIS_HOST redis_port = int(settings.REDIS_PORT) application.redis = Client(io_loop=io_loop) application.redis.authenticated = True application.redis.connect(redis_host, redis_port, callback=has_connected(application, io_loop)) application.redis.auth(settings.REDIS_PASSWORD) if __name__ == "__main__": if len(sys.argv) > 2: server_port = int(sys.argv[2]) else: server_port = int(sys.argv[1]) application.listen(server_port, address='0.0.0.0') io_loop.start()
def __init__(self, *args, **kwargs): super(MessageHandler, self).__init__(*args, **kwargs) self.r_server = Redis() self.redis = Client() self.redis.connect()