This is a decorator that you can put on a Python function that will temporarily fire up Twisted's reactor and run a function under Twisted. This is useful if most of your program doesn't use Twisted, but you have a function that must use Twisted.
Here's an example of using it:
Here's an example of using it:
@use_twistedHere's the decorator:
@defer.inlineCallbacks
def do_something_twisted():
value = yield do_something_else_twisted()
other_value = yield do_more_stuff()
defer.returnValue(value + other_value)
def use_twisted(twisted_function):Updated: Added code to prevent the decorator from being called twice.
"""This is a decorator to run a function under Twisted.
Temporarily fire up the reactor and run the function under Twisted.
It should return a deferred, of course.
Unfortunately, there's a bug in Twisted that only allows you to
start and stop the reactor once. See
http://jjinux.blogspot.com/2011/01/python-usetwisted-decorator.html.
Hence, this decorator will prevent you from calling it twice. So
sorry :(
"""
from twisted.python.failure import Failure
captured_value = [] # Think of this as a box.
def wrapper(*args, **kargs):
reactor.callLater(0, call_twisted_function, twisted_function, args,
kargs)
reactor.run()
assert captured_value
value = captured_value[0]
if isinstance(value, (Exception, Failure)):
raise value
else:
return value
def call_twisted_function(twisted_function, args, kargs):
deferred = twisted_function(*args, **kargs)
deferred.addBoth(capture_and_stop)
def capture_and_stop(value):
captured_value.append(value)
reactor.callLater(0, reactor.stop)
return value
if globals().get("_reactor_run", False):
raise AssertionError("The use_twisted decorator can only be used once")
else:
globals()["_reactor_run"] = True
return wrapper
Comments
Since we don't like Twisted being blamed for these kinds of crazy, impossible-to-debug scenarios where all of your sockets appear to be going haywire, we don't have a lot of incentive to "fix" the issue that reactors can't be restarted. (To be clear: this is not an issue with Twisted, it's just what happens when you start mixing asynchronous stream I/O with reentrant main loops.)
A more pressing bug is eliminating all usage of reactor.run() from our example code, and replacing it with a tool that can run a script in a context where the reactor is already running (like twistd, but simpler) so that new developers won't think that they're supposed to call it for every little thing.
It's not a feature when you call reactor.stop() once and it works, but when you call it a second time, it gets hung in an infinite loop. If a nice exception were raised, I'd call it a feature.
Hey, glyph ;)
I like to think I know what I'm doing, and that I'm not a mere clueless newbie. I need to use Twisted to look up some account data. I'm using a company library that requires Twisted. Once I get the data, I can completely exit Twisted and run in a completely synchronous manner. That's all working fine. I thought I could re-enter Twisted and exit properly (which in theory should work perfectly well), but it didn't work.
If you really, really don't want people starting and stopping the reactor twice, you should raise an exception when they try to do it. However, I see no reason why that should be the case. An expert user can enter and exit the reactor in the same way an expert user can mix Twisted with threads when necessary.
Yeah, that's what I had in mind too. Thanks!