Tornado 异步处理程序
我正在尝试在 Tornado 的 RequestHandler 中实现 get_current_user,但我需要在等待对数据库的异步调用时阻止该调用。使用 @tornado.web.asynchronous 修饰调用将不起作用,因为无论哪种方式, get_current_user 方法都会在异步查询完成并执行查询回调之前返回。
例如:
class MyHandler(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
self.write('example')
self.finish()
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
def query_cb(self, doc):
return doc or None
database.get(username='test', password='t3st', callback=query_cb)
@tornado.web.authenticated 调用 get_current_user,但始终收到“None”,因为 BaseHandler 没有时间响应。有没有一种方法,使用龙卷风,暂时阻止像上面这样的呼叫?
I am attempting to implement get_current_user in the RequestHandler for Tornado, but I need the call to block while waiting on the asynchronous call to my database. Decorating the call with @tornado.web.asynchronous will not work because either way the get_current_user method returns before the async query completes and the query callback is executed.
For example:
class MyHandler(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
self.write('example')
self.finish()
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
def query_cb(self, doc):
return doc or None
database.get(username='test', password='t3st', callback=query_cb)
@tornado.web.authenticated calls get_current_user, but always receives "None" because the BaseHandler does not have time to respond. Is there a way, using tornado, to temporarily block for a call such as the one above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行阻塞数据库操作,而不是上述非阻塞操作(tornado 附带有一个阻塞 mysql 库)。
来自 Tornado wiki 页面有关线程和并发的信息:
“同步执行并阻止 IOLoop。这最适合内存缓存和数据库查询之类的事情,这些查询在您的控制之下,并且应该始终保持快速。如果速度不快,可以通过向数据库添加适当的索引等来加快速度。 ”
https://github.com/facebook/tornado/wiki/Threading-and-concurrency
Do a blocking database operation instead of the non blocking described above (There is a blocking mysql lib shipped with tornado).
From the Tornado wiki page about threads and concurrency:
"Do it synchronously and block the IOLoop. This is most appropriate for things like memcache and database queries that are under your control and should always be fast. If it's not fast, make it fast by adding the appropriate indexes to the database, etc."
https://github.com/facebook/tornado/wiki/Threading-and-concurrency
当数据库返回异步响应时,让
get_current_user
返回一个Future
信号怎么样?How about having
get_current_user
return aFuture
that you signal when the asynchronous response from your database is returned?我认为 Tornado 允许您发出阻塞或非阻塞请求。
以下是 Tornado 用于两者的情况: https://bitbucket.org/nephics /tornado-couchdb/src/147579581b47/couch.py
免责声明:我对 Python 和 Tornado 知之甚少。
I thought Tornado allowed you to make either blocking or non-blocking requests.
Here is Tornado being used for both: https://bitbucket.org/nephics/tornado-couchdb/src/147579581b47/couch.py
Disclaimer: I know very little of Python and Tornado.