Callback inside inlineCallbacks function

Say I have a function like this:

def display(this, that):
    print this, that

and class:

class Runner(object):
    def __init__(self, callback):
        self.callback = callback
        self.loop = twisted.internet.task.LoopingCall(repeat)
        self.loop.start(0)

    @defer.inlineCallbacks
    def repeat(self):
        this = yield do_this()
        that = yield do_that()

        if this and that:
            # now I want to call the callback function
            yield self.callback(this, that) # makes sense?

runner = Runner(display)
reactor.run()

Basically, I want to create a Runner class that will perform some specific tasks, and every time it gets a result, it will call this callback function. Instead of creating a new function that does a certain thing, I want to create a generic class that does only one thing. For instance:

class TwitterReader(object):
    def __init__(self, callback):
        ...
        ...

    @defer.inlineCallbacks
    def get_messages(self):
        ...
        ...
        yield callback(messages)

class MessageFilter(object):
    def __init__(self):
        self.bad_messages = open('bad_messages.txt', 'w')
        self.twitter = TwitterReader(self.message_received)

    def message_received(messages):
        for message in messages:
            for bad_word in BAD_WORDS:
                if bad_word in message:
                    self.bad_messages.write(message)
                    break

I'm new to torsion. So I'm not sure if this is the right way to do this. It?

thank

+3
source share
2 answers

Your problem is what should be callbackinside .repeatself.callback

In addition, your example should work exactly as written.

+2
source

yield self.callback, , repeat. ( None), , - , . inlineCallbacks docs:

, , . , , , , Deferred.

(, inlineCallbacks), repeat . .

0

All Articles