如何从龙卷风中的收益中获取价值

how to get value from yield in tornado

我写了一个实时推送的websocket demo,但是我的代码不行...

我想从 yield ( uid = 89 ) return 获取值到 self.res['info']

怎么做?

websocket 演示:

class WSHandler(tornado.websocket.WebSocketHandler):
    res = {'code':200, 'info': ''}


    def initialize(self):
        self.c = tornadoredis.Client(host=CONFIG['REDIS_HOST'], port=CONFIG['REDIS_PORT'], password=CONFIG['REDIS_AUTH'])
        self.logintoken = self.get_argument('logintoken')
        self.noticeModel = noticeModel(self.logintoken, self.c)


    def open(self):
        print 'new connection'
        self.res['info'] = self.noticeModel.getNotice()
        print self.res
        if self.res['info']:
            r = self.res['info']
            print r.result()
            # self.write_message(json_encode(self.res))
        else:
            self.res['code'] = 500
            self.res['info'] = 'error'
            self.write_message(json_encode(self.res))

通知模型代码如下:

import tornado.gen
import tornado.web


class noticeModel :
 def __init__(self, logintoken, redisobj):
 self.logintoken = logintoken
 self.redisobj = redisobj


 # @tornado.web.asynchronous
 # @tornado.gen.coroutine
 @tornado.gen.engine
 def getNotice(self):
 self.uid = yield tornado.gen.Task(self.redisobj.get, self.logintoken)
 print "getNotice uid is %s"% self.uid

我在 iTerm 中 运行 它并得到这个输出:

new connection
{'info': None, 'code': 200}
getNotice uid is 89

使 WSHandler.open 成为协程,并产生 getNotice:

class WSHandler(tornado.websocket.WebSocketHandler):
    @tornado.gen.coroutine
    def open(self):
        print 'new connection'
        self.res['info'] = yield self.noticeModel.getNotice()

并将 getNotice 也设为协程:

class noticeModel :
   @tornado.gen.coroutine
   def getNotice(self):
       self.uid = yield tornado.gen.Task(self.redisobj.get, self.logintoken)

查看我的重构文章:

http://emptysqua.re/blog/refactoring-tornado-coroutines/