【问题标题】:Using inlineCallbacks使用 inlineCallbacks
【发布时间】:2013-01-20 16:30:43
【问题描述】:

我是 Twisted 的新手,我正在尝试编写一个简单的资源 显示来自数据库的名称列表,这是我的代码的一部分:

#code from my ContactResource class
def render_GET(self, request):
    def print_contacts(contacts, request):
        for c in contacts:
            request.write(c.name)
        if not request.finished:
            request.finish()
    d = Contact.find() #Contact is a Twistar DBObject subclass
    d.addCallback(print_contacts, request)
    return NOT_DONE_YET

我的问题是:如何更改此方法以使用 inlineCallbacks 装饰器?

【问题讨论】:

    标签: python twisted deferred


    【解决方案1】:

    编辑:我没有找到如何将 twisted.web 与 inlineCallbacks 结合使用的示例,但这里有两个建议。第一个更好,但我不确定它是否有效。

    @inlineCallbacks
    def render_GET(self, request):
        contacts = yield Contact.find() 
        defer.returnValue(''.join(c.name for c in contacts)
    
    
    @inlineCallbacks
    def render_GET(self, request):
        contacts = yield Contact.find() 
        for c in contacts:
            request.write(c.name)
        if not request.finished:
            request.finish()
        defer.returnValue(NOT_DONE_YET)
    

    【讨论】:

    • 感谢@schlamar 的示例,但它不起作用。这会引发“请求未返回字符串”错误。
    • @user2043932 编辑了我的答案。
    【解决方案2】:

    render_GET 方法可能不会返回 Deferred。它可能只返回一个字符串或NOT_DONE_YET。任何用inlineCallbacks 装饰的方法都将返回Deferred。所以,你不能用inlineCallbacks装饰render_GET

    当然,没有什么能阻止您在render_GET 中调用您想要的任何其他函数,包括返回Deferred 的函数。只需将Deferred 扔掉,而不是从render_GET 返回它(当然,请确保Deferred 永远不会因失败而触发,或者将其扔掉可能会丢失一些错误报告...)。

    所以,例如:

    @inlineCallbacks
    def _renderContacts(self, request):
        contacts = yield Contact.find() 
        for c in contacts:
            request.write(c.name)
        if not request.finished:
            request.finish()
    
    
    def render_GET(self, request):
        self._renderContacts(request)
        return NOT_DONE_YET
    

    如果您打算使用 Twisted 进行任何严肃的 Web 开发,我建议至少看看 txyogaklein。即使您不想使用它们,它们也应该为您提供一些关于如何构建代码并完成类似这样的各种常见任务的好主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      相关资源
      最近更新 更多