本文介绍了使用inlineCallbacks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Twisted的新手,我试图编写一个简单的资源,其中
显示数据库中的名称列表,这是我的代码的一部分:

I'm new to Twisted and I'm trying to write a simple resource whichdisplays a list of names from a database, here's a part of my code:

#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装饰器?

My question is: how can I change this method to use the inlineCallbacks decorator?

推荐答案

A render_GET 方法可能不会返回 Deferred 。它只能返回一个字符串或 NOT_DONE_YET 。用 inlineCallbacks 装饰的任何方法都将返回 Deferred 。因此,您可能无法使用 inlineCallbacks 装饰 render_GET

A render_GET method may not return a Deferred. It may only return a string or NOT_DONE_YET. Any method decorated with inlineCallbacks will return a Deferred. So, you may not decorate render_GET with inlineCallbacks.

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

Of course, nothing stops you from calling any other function you want in render_GET, including one that returns a Deferred. Just throw the Deferred away instead of returning it from render_GET (of course, make sure that the Deferred never fires with a failure, or by throwing it away you may be missing some error reporting...).

因此,对于例如:

@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

我建议至少看看和如果您要进行任何认真的Web开发与扭曲。即使您不想使用它们,它们也应该给您一些有关如何构造代码并完成诸如此类的常见任务的好主意。

I recommend at least taking a look at txyoga and klein if you're going to be doing any serious web development with Twisted. Even if you don't want to use them, they should give you some good ideas about how you can structure your code and accomplish various common tasks like this one.

这篇关于使用inlineCallbacks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 05:52