[英]Tornado, Accessing additional data in callback function?
I have just started a project using Tornado, and asyncmongo. 我刚刚使用Tornado和asyncmongo启动了一个项目。
I have a handler with an async method. 我有一个带有异步方法的处理程序。 Inside I am querying mongo for some words:
在内部,我正在向mongo查询一些单词:
@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
In my callback method I need the original word to sort the mongo results accurately. 在我的回调方法中,我需要使用原始单词对mongo结果进行准确排序。
I found this post which uses functools.partial
to accomplish this, by allowing me to pass additional parameters to the callback method 我发现这篇文章使用
functools.partial
通过允许我将其他参数传递给回调方法来完成此任务
I was wondering if there are any adverse affects to setting an instance attribute in the get
method and accessing it in _on_response
? 我想知道是否会对在
get
方法中设置实例属性并在_on_response
访问它产生任何不利影响? THank you 谢谢
@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
Use tornado.gen and you sidestep the problem completely 使用tornado.gen,您完全可以避免问题
http://www.tornadoweb.org/documentation/gen.html?highlight=tornado.gen#tornado.gen http://www.tornadoweb.org/documentation/gen.html?highlight=tornado.gen#tornado.gen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.