tornado.platform.twisted — Bridges between Twisted and Tornado¶
Bridges between the Twisted reactor and Tornado IOLoop.
This module lets you run applications and libraries written for Twisted in a Tornado application. It can be used in two modes, depending on which library’s underlying event loop you want to use.
This module has been tested with Twisted versions 11.0.0 and newer.
Twisted on Tornado¶
-
class
tornado.platform.twisted.TornadoReactor(io_loop=None)[source]¶ Twisted reactor built on the Tornado IOLoop.
TornadoReactorimplements the Twisted reactor interface on top of the Tornado IOLoop. To use it, simply callinstallat the beginning of the application:import tornado4.platform.twisted tornado4.platform.twisted.install() from twisted.internet import reactor
When the app is ready to start, call
IOLoop.current().start()instead ofreactor.run().It is also possible to create a non-global reactor by calling
tornado4.platform.twisted.TornadoReactor(io_loop). However, if theIOLoopand reactor are to be short-lived (such as those used in unit tests), additional cleanup may be required. Specifically, it is recommended to call:reactor.fireSystemEvent('shutdown') reactor.disconnectAll()
before closing the
IOLoop.Changed in version 4.1: The
io_loopargument is deprecated.-
seconds()[source]¶ time() -> floating point number
Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
-
getDelayedCalls()[source]¶ Return all the outstanding delayed calls in the system. They are returned in no particular order. This method is not efficient – it is really only meant for test cases.
@return: A list of outstanding delayed calls. @type: L{list} of L{DelayedCall}
-
callFromThread(f, *args, **kw)[source]¶ See L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}.
-
installWaker()[source]¶ Install a `waker’ to allow threads and signals to wake up the IO thread.
We use the self-pipe trick (http://cr.yp.to/docs/selfpipe.html) to wake the reactor. On Windows we use a pair of sockets.
-
-
tornado.platform.twisted.install(io_loop=None)[source]¶ Install this package as the default Twisted reactor.
install()must be called very early in the startup process, before most other twisted-related imports. Conversely, because it initializes theIOLoop, it cannot be called beforefork_processesor multi-processstart. These conflicting requirements make it difficult to useTornadoReactorin multi-process mode, and an external process manager such assupervisordis recommended instead.Changed in version 4.1: The
io_loopargument is deprecated.
Tornado on Twisted¶
-
class
tornado.platform.twisted.TwistedIOLoop[source]¶ IOLoop implementation that runs on Twisted.
TwistedIOLoopimplements the Tornado IOLoop interface on top of the Twisted reactor. Recommended usage:from tornado4.platform.twisted import TwistedIOLoop from twisted.internet import reactor TwistedIOLoop().install() # Set up your tornado application as usual using `IOLoop.instance` reactor.run()
Uses the global Twisted reactor by default. To create multiple
TwistedIOLoopsin the same process, you must pass a unique reactor when constructing each one.Not compatible with
tornado4.process.Subprocess.set_exit_callbackbecause theSIGCHLDhandlers used by Tornado and Twisted conflict with each other.See also
tornado4.ioloop.IOLoop.install()for general notes on installing alternative IOLoops.-
initialize(reactor=None, **kwargs)[source]¶ Initialize a
Configurablesubclass instance.Configurable classes should use
initializeinstead of__init__.Changed in version 4.2: Now accepts positional arguments in addition to keyword arguments.
-
close(all_fds=False)[source]¶ Closes the
IOLoop, freeing any resources used.If
all_fdsis true, all file descriptors registered on the IOLoop will be closed (not just the ones created by theIOLoopitself).Many applications will only use a single
IOLoopthat runs for the entire lifetime of the process. In that case closing theIOLoopis not necessary since everything will be cleaned up when the process exits.IOLoop.closeis provided mainly for scenarios such as unit tests, which create and destroy a large number ofIOLoops.An
IOLoopmust be completely stopped before it can be closed. This means thatIOLoop.stop()must be called andIOLoop.start()must be allowed to return before attempting to callIOLoop.close(). Therefore the call toclosewill usually appear just after the call tostartrather than near the call tostop.Changed in version 3.1: If the
IOLoopimplementation supports non-integer objects for “file descriptors”, those objects will have theirclosemethod whenall_fdsis true.
-
add_handler(fd, handler, events)[source]¶ Registers the given handler to receive the given events for
fd.The
fdargument may either be an integer file descriptor or a file-like object with afileno()method (and optionally aclose()method, which may be called when theIOLoopis shut down).The
eventsargument is a bitwise or of the constantsIOLoop.READ,IOLoop.WRITE, andIOLoop.ERROR.When an event occurs,
handler(fd, events)will be run.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
update_handler(fd, events)[source]¶ Changes the events we listen for
fd.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
remove_handler(fd)[source]¶ Stop listening for events on
fd.Changed in version 4.0: Added the ability to pass file-like objects in addition to raw file descriptors.
-
start()[source]¶ Starts the I/O loop.
The loop will run until one of the callbacks calls
stop(), which will make the loop stop after the current event iteration completes.
-
stop()[source]¶ Stop the I/O loop.
If the event loop is not currently running, the next call to
start()will return immediately.To use asynchronous methods from otherwise-synchronous code (such as unit tests), you can start and stop the event loop like this:
ioloop = IOLoop() async_method(ioloop=ioloop, callback=ioloop.stop) ioloop.start()
ioloop.start()will return afterasync_methodhas run its callback, whether that callback was invoked before or afterioloop.start.Note that even after
stophas been called, theIOLoopis not completely stopped untilIOLoop.starthas also returned. Some work that was scheduled before the call tostopmay still be run before theIOLoopshuts down.
-
add_timeout(deadline, callback, *args, **kwargs)[source]¶ Runs the
callbackat the timedeadlinefrom the I/O loop.Returns an opaque handle that may be passed to
remove_timeoutto cancel.deadlinemay be a number denoting a time (on the same scale asIOLoop.time, normallytime.time), or adatetime.timedeltaobject for a deadline relative to the current time. Since Tornado 4.0,call_lateris a more convenient alternative for the relative case since it does not require a timedelta object.Note that it is not safe to call
add_timeoutfrom other threads. Instead, you must useadd_callbackto transfer control to theIOLoop’s thread, and then calladd_timeoutfrom there.Subclasses of IOLoop must implement either
add_timeoutorcall_at; the default implementations of each will call the other.call_atis usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must useadd_timeoutinstead.Changed in version 4.0: Now passes through
*argsand**kwargsto the callback.
-
remove_timeout(timeout)[source]¶ Cancels a pending timeout.
The argument is a handle as returned by
add_timeout. It is safe to callremove_timeouteven if the callback has already been run.
-
add_callback(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time, except from a signal handler. Note that this is the only method in
IOLoopthat makes this thread-safety guarantee; all other interaction with theIOLoopmust be done from thatIOLoop’s thread.add_callback()may be used to transfer control from other threads to theIOLoop’s thread.To add a callback from a signal handler, see
add_callback_from_signal.
-
add_callback_from_signal(callback, *args, **kwargs)[source]¶ Calls the given callback on the next I/O loop iteration.
Safe for use from a Python signal handler; should not be used otherwise.
Callbacks added with this method will be run without any
stack_context, to avoid picking up the context of the function that was interrupted by the signal.
-
Twisted DNS resolver¶
-
class
tornado.platform.twisted.TwistedResolver[source]¶ Twisted-based asynchronous resolver.
This is a non-blocking and non-threaded resolver. It is recommended only when threads cannot be used, since it has limitations compared to the standard
getaddrinfo-basedResolverandThreadedResolver. Specifically, it returns at most one result, and arguments other thanhostandfamilyare ignored. It may fail to resolve whenfamilyis notsocket.AF_UNSPEC.Requires Twisted 12.1 or newer.
Changed in version 4.1: The
io_loopargument is deprecated.-
initialize(io_loop=None)[source]¶ Initialize a
Configurablesubclass instance.Configurable classes should use
initializeinstead of__init__.Changed in version 4.2: Now accepts positional arguments in addition to keyword arguments.
-
resolve(host, port, family=0)[source]¶ Resolves an address.
The
hostargument is a string which may be a hostname or a literal IP address.Returns a
Futurewhose result is a list of (family, address) pairs, where address is a tuple suitable to pass tosocket.connect(i.e. a(host, port)pair for IPv4; additional fields may be present for IPv6). If acallbackis passed, it will be run with the result as an argument when it is complete.Raises: IOError – if the address cannot be resolved. Changed in version 4.4: Standardized all implementations to raise
IOError.
-