Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inlineCallbacks

I'm new to Twisted and I'm trying to write a simple resource which displays 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

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

like image 746
user2043932 Avatar asked Feb 05 '13 16:02

user2043932


1 Answers

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.

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...).

So, for example:

@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

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.

like image 94
Jean-Paul Calderone Avatar answered Nov 11 '22 22:11

Jean-Paul Calderone