tornado-redis:LPOP有效,但BLPOP没有?

时间:2015-03-10 16:11:45

标签: python redis tornado

Tornado和Redis的新手 我发现有人在这里遇到同样的问题,tornado-redis: RPOP works but BRPOP doesn't? 但我仍然不明白为什么,以及如何解决我的问题

代码打击工作正常

#coding:utf-8
import random
import time
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
from uuid import uuid4
# import redis
from tornado.escape import json_encode
import tornado.gen
import tornadoredis

class noticePush(tornado.web.RequestHandler):

    def initialize(self):
        print 'initialize'

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        print 'go here'
        try:

            **uid = self.get_argument('uid')
            # key = u'test_comet%s'%uid
            key = 'test_comet1'
            c = tornadoredis.Client(host='127.0.0.1', port=6379,password='psw')
            print key
            res = yield tornado.gen.Task(c.blpop, key, 0)**
            print res
            if res :
                self.finish(json_encode(res))
            else :
                self.finish('None')

        except Exception, e :
            print e
        pass


class Application(tornado.web.Application):
    def __init__(self):

        handlers = [
            (r'/', noticePush)
        ]

        settings = {
            'template_path': 'templates',
            'static_path': 'static',
            'debug': True
        }

        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':
    tornado.options.parse_command_line()

    app = Application()
    server = tornado.httpserver.HTTPServer(app)
    server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()

但是,我尝试使用get_argument作为键,blpop永远不会返回任何数据

**uid = self.get_argument('uid')
key = 'test_comet' + uid
c = tornadoredis.Client(host='127.0.0.1', port=6379, password='psw')
print key
res = yield tornado.gen.Task(c.blpop, key, 0)**
print res
if res :
    self.finish(json_encode(res))
else :
    self.finish('None')

1 个答案:

答案 0 :(得分:0)

我尝试阅读tornadoredis代码,找到blpop def并找到原因

def blpop(self, keys, timeout=0, callback=None):
        tokens = to_list(keys)
        tokens.append(timeout)
        self.execute_command('BLPOP', *tokens, callback=callback)

def to_list(source):
    if isinstance(source, str):
        return [source]
    else:
        return list(source)
重要的是 str_key ='test_comet',type(key) - >海峡 unicode_key ='test_comet'+ uid,type(key) - >的unicode

当我编码unicode_key.encode('utf-8')时,代码工作正常!