【问题标题】:Understanding tornado coroutine decorator + twitter authentication了解tornado协程装饰器+推特认证
【发布时间】:2013-05-25 10:43:07
【问题描述】:

我是 Tornado 的新手,正在尝试让简单的 OAuth twitter 身份验证正常工作。根据文档,我需要按如下方式设置身份验证处理程序:

class TwitterAuthHandler(BaseHandler, tornado.auth.TwitterMixin):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        if self.get_argument("oauth_token", None):
            user = yield self.get_authenticated_user()
            if not user:
                raise tornado.web.HTTPError(500, "Twitter auth failed")
            self.set_secure_cookie("twitter_user", user)
            self.redirect("/")
        else:
            self.authenticate_redirect()

但是,当我运行此代码时,我得到了错误:

  File "/Library/Python/2.7/site-packages/tornado/web.py", line 485, in redirect
    raise Exception("Cannot redirect after headers have been written")
Exception: Cannot redirect after headers have been written

这似乎是因为异步调用没有正确运行,self.authenticate_redirect() 行引发了异常。如果我用@tornado.gen.engine 替换@tornado.gen.coroutine 一切正常。但是,我知道gen.engine 是旧的做事方式,应该首选gen.coroutine,因为它会返回未来。

我还尝试将对self.get_authenticated_user() 的调用封装在tornado.gen.Task() 中。我不确定何时需要使用 gen.Task() 进行包装,但在这种情况下这似乎没有任何区别。

这段代码有什么问题,为什么gen.coroutine 失败但gen.engine 工作?

【问题讨论】:

    标签: python asynchronous twitter tornado coroutine


    【解决方案1】:

    检查后我认为这可能是一个错误。将示例代码发布到 python-tornado Google Group 的此线程中:https://groups.google.com/forum/?fromgroups#!topic/python-tornado/YypdSaXsM_Y 确认:

    auth*_redirect 方法不返回 Futures 所以它们不能是 产生了,但他们应该。作为目前的解决方法,您可以继续 使用@gen.engine 并调用这些方法而不屈服。

    【讨论】:

    • Hmmm... 有趣的是,尽管 Tornado 文档本身中的代码示例存在问题(请参阅 here),但该错误仍有待解决。但是,很高兴知道原因是什么,并且我对gen.coroutinegen.engine 的理解并没有发疯。感谢您的帮助!
    • 这个问题解决了吗?
    • @evan54,显然它已在version 3.1 中得到修复:“tornado.auth 混合类中的 authenticate_redirect 和 authorize_redirect 方法现在都返回 Futures。”
    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多