Tornado,如何在回调函数中访问额外数据?
我刚开始用Tornado和asyncmongo做一个项目。
我有一个处理器,里面有一个异步方法。在这个方法里,我正在查询MongoDB来获取一些单词:
@tornado.web.asynchronous
def get(self):
word = self.get_argument('word', None)
if not word:
self.write('{}')
self.finish()
self.db.spanish_dict.find({'$or': [{'word': word}, {'stem': word}]},
callback=self._on_response)
def _on_response(self, response, error):
# need to sort response by relevancy
在我的回调方法中,我需要原始的单词,以便准确地对MongoDB的结果进行排序。
我找到了一篇帖子,里面提到使用functools.partial
来实现这个功能,这样我就可以在回调方法中传递额外的参数。
我想知道在get
方法中设置一个实例属性,然后在_on_response
中访问它,会不会有什么不好的影响?谢谢
@tornado.web.asynchronous
def get(self):
word = self.get_argument('word', None)
if not word:
self.write('{}')
self.finish()
self.word = word
self.db.spanish_dict.find({'$or': [{'word': word}, {'stem': word}]},
callback=self._on_response)
def _on_response(self, response, error):
# need to sort response by relevancy
# will self.word always be accurate?
self.word
1 个回答
1
使用tornado.gen,你就可以完全避开这个问题。
http://www.tornadoweb.org/documentation/gen.html?highlight=tornado.gen#tornado.gen