9.1 KiB
API
The API is identical whether you're using Twisted or asyncio under
the hood. Two bool variables are available if you need to
know which framework is in use, and two helpers to enforce one or the
other framework.
Explicitly Selecting a Framework
Until you explicitly select a framework, all txaio API methods just
throw a usage error. So, you must call .use_twisted() or
.use_asyncio() as appropriate. These will fail with
ImportError if you don't have the correct dependencies.
import txaio
txaio.use_twisted()
txaio.use_asyncio()Set an Event Loop / Reactor
You can set txaio.config.loop to either an EventLoop
instance (if using asyncio) or an explicit reactor (if using Twisted).
By default, reactor is imported from
twisted.internet on the first call_later
invocation. For asyncio, asyncio.get_event_loop() is called
at import time.
If you've installed your reactor before import txaio you
shouldn't need to do anything.
Note that under Twisted, only the IReactorTime interface is required.
Test Helpers
Test utilities are in txaio.testutil. There is a
context-manager for testing delayed calls; see
test_call_later.py for an example.
txaio.testutil
txaio module
Trueonly if we're using Twisted as our underlying event framework
Trueonly if we're using asyncio as our underlying event framework
Select
asyncioframework (uses trollius/tulip on Pythons that lack asyncio).
Select the Twisted framework (will fail if Twisted is not installed).
Create and return a new framework-specific future object. On asyncio this returns a Future, on Twisted it returns a Deferred.
- param value
if not
None, the future is already fulfilled, with the given result.- param error
if not
Nonethen the future is already failed, with the given error.- type error
class:IFailedFuture or Exception
- raises ValueError
if both
valueanderrorare provided.- return
Call
funcwith the provided arguments and keyword arguments, and always return a Future/Deferred. Iffuncitself returns a future, that is directly returned. If it immediately succeed or failed then an already-resolved Future/Deferred is returned instead.This allows you to write code that calls functions (e.g. possibly provided from user-code) and treat them uniformly. For example:
p = txaio.as_future(some_function, 1, 2, key='word') txaio.add_callbacks(p, do_something, it_failed)You therefore don't have to worry if the underlying function was itself asynchronous or not -- your code always treats it as asynchronous.
Resolve the given future as failed. This will call any errbacks registered against this Future/Deferred. On Twisted, the errback is called with a bare Failure instance; on asyncio we provide an object that implements
IFailedFuturebecause there is no equivalent in asyncio (this mimics part of the Failure API).
Resolve the given future with the provided value. This triggers any callbacks registered against this Future/Deferred.
Adds the provided callback and/or errback to the given future. To add multiple callbacks, call this method multiple times. For example, to add just an errback, call
add_callbacks(p, None, my_errback)Note that
txaiodoesn't do anything special with regards to callback or errback chaining -- it is highly recommended that you always return the incoming argument unmodified in your callback/errback so that Twisted and asyncio behave the same. For example:def callback_or_errback(value): # other code return value
- raises ValueError
if both callback and errback are None
Takes an
txaio.IFailedFutureinstance and returns a formatted message suitable to show to a user. This will be astrwith no newlines for the form:{exception_name}: {error_message}whereerror_messageis the result of runningstr()on the exception instance (under asyncio) or the result of.getErrorMessage()on the Failure under Twisted.
Take an
txaio.IFailedFutureinstance and returns the Pythontracebackinstance associated with the failure.
Take an
txaio.IFailedFutureinstance and returns a formatted string showing the traceback. Typically, this will have many newlines in it and look like a "normal" Python traceback.
This calls the function
funcwith the given parameters at the specified time in the future. Although asyncio doesn't directly support kwargs withloop.call_laterwe wrap it in afunctools.partial, as asyncio documentation suggests.Note: see
txaio.make_batched_timerif you may have a lot of timers, and their absolute accuracy isn't very important.
- param delay
how many seconds in the future to make the call
- returns
The underlying library object, which will at least have a
.cancel()method on it. It's really IDelayedCall in Twisted and a Handle in asyncio.
This returns an object implementing
txaio.IBatchedTimersuch that any.call_latercalls done through it (instead of viatxaio.call_later) will be "quantized" into buckets and processed inchunk_sizebatches "near" the time they are supposed to fire.seconds_per_bucketis only accurate to "milliseconds".When there are "tens of thousands" of outstanding timers, CPU usage can become a problem -- if the accuracy of the timers isn't very important, using "batched" timers can greatly reduce the number of "real" delayed calls in the event loop.
For example, Autobahn uses this feature for auto-ping timeouts, where the exact time of the event isn't extremely important -- but there are 2 outstanding calls per connection.
Returns a new Future that waits for the results from all the futures provided.
The Future/Deferred returned will callback with a list the same length as
futurescontaining either the return value from each future, or anIFailedFuture/Failure instance if it failed.Note that on Twisted, we use DeferredList which usually returns a list of 2-tuples of
(status, value). We do inject a callback that unpacks this list to be just the value (or Failure) so that your callback can be identical on Twisted and asyncio.
Creates and returns an instance of
ILogger. This can pick up context from where it's instantiated (e.g. the containing class or module) so the best way to use this is to create a logger for each class that produces logs; see the example inILogger's documentation
txaio.interfaces.ILogger
txaio.interfaces.IFailedFuture