Using inlineCallbacks

I'm new to Twisted, and I'm trying to write a simple resource that displays a list of names from a database, here is 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?

+8
python twisted deferred
source share
2 answers

A render_GET method cannot return Deferred . It can only return a string or NOT_DONE_YET . Any method decorated with inlineCallbacks will return a Deferred . Thus, you cannot decorate render_GET with inlineCallbacks .

Of course, nothing prevents you from calling any other function that you want in render_GET , including the one that returns Deferred . Just drop Deferred and not return it from render_GET (of course, make sure that Deferred never fails or throws it, maybe you are missing error messages ...).

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 that you at least take a look at txyoga and klein if you intend to do serious web development with Twisted. Even if you don't want to use them, they should give you some good ideas on how you can structure your code and perform various common tasks, such as this one.

+11
source share

Edit: I did not find an example of how to combine twisted.web with inlineCallbacks, but here are two suggestions. The first is preferable, but I'm not sure if it works.

 @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) 
-2
source share

All Articles