tornado.gen — Simplify asynchronous code¶
tornado.gen
is a generator-based interface to make it easier towork in an asynchronous environment. Code using the gen
moduleis technically asynchronous, but it is written as a single generatorinstead of a collection of separate functions.
For example, the following asynchronous handler:
- class AsyncHandler(RequestHandler):
- @asynchronous
- def get(self):
- http_client = AsyncHTTPClient()
- http_client.fetch("http://example.com",
- callback=self.on_fetch)
- def on_fetch(self, response):
- do_something_with_response(response)
- self.render("template.html")
could be written with gen
as:
- class GenAsyncHandler(RequestHandler):
- @gen.coroutine
- def get(self):
- http_client = AsyncHTTPClient()
- response = yield http_client.fetch("http://example.com")
- do_something_with_response(response)
- self.render("template.html")
Most asynchronous functions in Tornado return a Future
;yielding this object returns its result
.
You can also yield a list or dict of Futures
, which will bestarted at the same time and run in parallel; a list or dict of results willbe returned when they are all finished:
- @gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response1, response2 = yield [http_client.fetch(url1),
http_client.fetch(url2)]
response_dict = yield dict(response3=http_client.fetch(url3),
response4=http_client.fetch(url4))
response3 = response_dict['response3']
response4 = response_dict['response4']
If the singledispatch
library is available (standard inPython 3.4, available via the singledispatch package on olderversions), additional types of objects may be yielded. Tornado includessupport for asyncio.Future
and Twisted’s Deferred
class whentornado.platform.asyncio
and tornado.platform.twisted
are imported.See the convert_yielded
function to extend this mechanism.
在 3.2 版更改: Dict support added.
在 4.1 版更改: Support added for yielding asyncio
Futures and Twisted Deferredsvia singledispatch
.
Decorators¶
tornado.gen.
coroutine
(func, replace_callback=True)[源代码]¶
Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrappedin either this decorator orengine
.
Coroutines may “return” by raising the special exceptionReturn(value)
. In Python 3.3+, it is also possible forthe function to simply use thereturn value
statement (prior toPython 3.3 generators were not allowed to also return values).In all versions of Python a coroutine that simply wishes to exitearly may use thereturn
statement without a value.
Functions with this decorator return aFuture
. Additionally,they may be called with acallback
keyword argument, whichwill be invoked with the future’s result when it resolves. If thecoroutine fails, the callback will not be run and an exceptionwill be raised into the surroundingStackContext
. Thecallback
argument is not visible inside the decoratedfunction; it is handled by the decorator itself.
From the caller’s perspective,@gen.coroutine
is similar tothe combination of@returnfuture
and@gen.engine
.
警告
When exceptions occur inside a coroutine, the exceptioninformation will be stored in theFuture
object. You mustexamine the result of theFuture
object, or the exceptionmay go unnoticed by your code. This means yielding the functionif called from another coroutine, using something likeIOLoop.run_sync
for top-level calls, or passing theFuture
toIOLoop.add_future
.
tornado.gen.
engine
(_func)[源代码]¶
Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to becompatible with versions of Tornado older than 3.0 thecoroutine
decorator is recommended instead.
This decorator is similar tocoroutine
, except it does notreturn aFuture
and thecallback
argument is not treatedspecially.
In most cases, functions decorated withengine
should takeacallback
argument and invoke it with their result whenthey are finished. One notable exception is theRequestHandler
HTTP verb methods,which useself.finish()
in place of a callback argument.
Utility functions¶
- exception
tornado.gen.
Return
(value=None)[源代码]¶
Special exception to return a value from acoroutine
.
If this exception is raised, its value argument is used as theresult of the coroutine:- @gen.coroutine
def fetchjson(url):
response = yield AsyncHTTPClient().fetch(url)
raise gen.Return(json_decode(response.body))
In Python 3.3, this exception is no longer necessary: thereturn
statement can be used directly to return a value (previouslyyield
andreturn
with a value could not be combined in thesame function).
By analogy with the return statement, the value argument is optional,but it is never necessary toraise gen.Return()
. Thereturn
statement can be used with no arguments instead.- @gen.coroutine
tornado.gen.
with_timeout
(_timeout, future, io_loop=None, quiet_exceptions=())[源代码]¶
Wraps aFuture
(or other yieldable object) in a timeout.
RaisesTimeoutError
if the input future does not complete beforetimeout
, which may be specified in any form allowed byIOLoop.add_timeout
(i.e. adatetime.timedelta
or an absolute timerelative toIOLoop.time
)
If the wrappedFuture
fails after it has timed out, the exceptionwill be logged unless it is of a type contained inquietexceptions
(which may be an exception type or a sequence of types).
Does not supportYieldPoint
subclasses.
4.0 新版功能.
在 4.1 版更改: Added thequiet_exceptions
argument and the logging of unhandledexceptions.
在 4.4 版更改: Added support for yieldable objects other thanFuture
.
tornado.gen.
sleep
(_duration)[源代码]¶
Return aFuture
that resolves after the given number of seconds.
When used withyield
in a coroutine, this is a non-blockinganalogue totime.sleep
(which should not be used in coroutinesbecause it is blocking):- yield gen.sleep(0.5)
Note that calling this function on its own does nothing; you mustwait on theFuture
it returns (usually by yielding it).
4.1 新版功能.- yield gen.sleep(0.5)
tornado.gen.
moment
¶
A special object which may be yielded to allow the IOLoop to run forone iteration.
This is not needed in normal use but it can be helpful in long-runningcoroutines that are likely to yield Futures that are ready instantly.
Usage:yield gen.moment
4.0 新版功能.
- class
tornado.gen.
WaitIterator
(*args, **kwargs)[源代码]¶
Provides an iterator to yield the results of futures as they finish.
Yielding a set of futures like this:results = yield [future1, future2]
pauses the coroutine until bothfuture1
andfuture2
return, and then restarts the coroutine with the results of bothfutures. If either future is an exception, the expression willraise that exception and all the results will be lost.
If you need to get the result of each future as soon as possible,or if you need the result of some futures even if others produceerrors, you can useWaitIterator
:- waititerator = gen.WaitIterator(future1, future2)
while not wait_iterator.done():
try:
result = yield wait_iterator.next()
except Exception as e:
print("Error {} from {}".format(e, wait_iterator.current_future))
else:
print("Result {} received from {} at {}".format(
result, wait_iterator.current_future,
wait_iterator.current_index))
Because results are returned as soon as they are available theoutput from the iterator _will not be in the same order as theinput arguments. If you need to know which future produced thecurrent result, you can use the attributesWaitIterator.currentfuture
, orWaitIterator.current_index
to get the index of the future from the input list. (if keywordarguments were used in the construction of theWaitIterator
,current_index
will use the corresponding keyword).
On Python 3.5,WaitIterator
implements the async iteratorprotocol, so it can be used with theasync for
statement (notethat in this version the entire iteration is aborted if any valueraises an exception, while the previous example can continue pastindividual errors):- async for result in gen.WaitIterator(future1, future2):
print("Result {} received from {} at {}".format(
result, wait_iterator.current_future,
wait_iterator.current_index))
4.1 新版功能.
在 4.3 版更改: Addedasync for
support in Python 3.5.- waititerator = gen.WaitIterator(future1, future2)
tornado.gen.
multi
(_children, quiet_exceptions=())[源代码]¶
Runs multiple asynchronous operations in parallel.children
may either be a list or a dict whose values areyieldable objects.multi()
returns a new yieldableobject that resolves to a parallel structure containing theirresults. Ifchildren
is a list, the result is a list ofresults in the same order; if it is a dict, the result is a dictwith the same keys.
That is,results = yield multi(listof_futures)
is equivalentto:- results = []
for future in list_of_futures:
results.append(yield future)
If any children raise exceptions,multi()
will raise the firstone. All others will be logged, unless they are of typescontained in thequiet_exceptions
argument.
If any of the inputs areYieldPoints
, the returnedyieldable object is aYieldPoint
. Otherwise, returns aFuture
.This means that the result ofmulti
can be used in a nativecoroutine if and only if all of its children can be.
In ayield
-based coroutine, it is not normally necessary tocall this function directly, since the coroutine runner willdo it automatically when a list or dict is yielded. However,it is necessary inawait
-based coroutines, or to passthequiet_exceptions
argument.
This function is available under the namesmulti()
andMulti()
for historical reasons.
在 4.2 版更改: If multiple yieldables fail, any exceptions after the first(which is raised) will be logged. Added thequiet_exceptions
argument to suppress this logging for selected exception types.
在 4.3 版更改: Replaced the classMulti
and the functionmulti_future
with a unified functionmulti
. Added support for yieldablesother thanYieldPoint
andFuture
.- results = []
tornado.gen.
multi_future
(_children, quiet_exceptions=())[源代码]¶
Wait for multiple asynchronous futures in parallel.
This function is similar tomulti
, but does not supportYieldPoints
.
4.0 新版功能.
在 4.2 版更改: If multipleFutures
fail, any exceptions after the first (which israised) will be logged. Added thequietexceptions
argument to suppress this logging for selected exception types.
4.3 版后已移除: Usemulti
instead.
tornado.gen.
Task
(_func, *args, **kwargs)[源代码]¶
Adapts a callback-based asynchronous function for use in coroutines.
Takes a function (and optional additional arguments) and runs it withthose arguments plus acallback
keyword argument. The argument passedto the callback is returned as the result of the yield expression.
在 4.0 版更改:gen.Task
is now a function that returns aFuture
, instead ofa subclass ofYieldPoint
. It still behaves the same way whenyielded.
- class
tornado.gen.
Arguments
¶
The result of aTask
orWait
whose callback had more than oneargument (or keyword arguments).
TheArguments
object is acollections.namedtuple
and can beused either as a tuple(args, kwargs)
or an object with attributesargs
andkwargs
.
tornado.gen.
convertyielded
(args, *kw)[源代码]¶
Convert a yielded object into aFuture
.
The default implementation accepts lists, dictionaries, and Futures.
If thesingledispatch
library is available, this functionmay be extended to support additional types. For example:- @convert_yielded.register(asyncio.Future)
def (asynciofuture):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
4.1 新版功能.- @convert_yielded.register(asyncio.Future)
tornado.gen.
maybe_future
(_x)[源代码]¶
Convertsx
into aFuture
.
Ifx
is already aFuture
, it is simply returned; otherwiseit is wrapped in a newFuture
. This is suitable for use asresult = yield gen.maybe_future(f())
when you don’t know whetherf()
returns aFuture
or not.
4.3 版后已移除: This function only handlesFutures
, not other yieldable objects.Instead ofmaybe_future
, check for the non-future result typesyou expect (often justNone
), andyield
anything unknown.
Legacy interface¶
Before support for Futures
was introduced in Tornado 3.0,coroutines used subclasses of YieldPoint
in their yield
expressions.These classes are still supported but should generally not be usedexcept for compatibility with older interfaces. None of these classesare compatible with native (await
-based) coroutines.
- class
tornado.gen.
YieldPoint
[源代码]¶
Base class for objects that may be yielded from the generator.
4.0 版后已移除: UseFutures
instead.start
(runner)[源代码]¶
Called by the runner after the generator has yielded.
No other methods will be called on this object beforestart
.
- _class
tornado.gen.
Callback
(key)[源代码]¶
Returns a callable object that will allow a matchingWait
to proceed.
The key may be any value suitable for use as a dictionary key, and isused to matchCallbacks
to their correspondingWaits
. The keymust be unique among outstanding callbacks within a single run of thegenerator function, but may be reused across different runs of the samefunction (so constants generally work fine).
The callback may be called with zero or one arguments; if an argumentis given it will be returned byWait
.
4.0 版后已移除: UseFutures
instead.
- class
tornado.gen.
Wait
(key)[源代码]¶
Returns the argument passed to the result of a previousCallback
.
4.0 版后已移除: UseFutures
instead.
- class
tornado.gen.
WaitAll
(keys)[源代码]¶
Returns the results of multiple previousCallbacks
.
The argument is a sequence ofCallback
keys, and the result isa list of results in the same order.WaitAll
is equivalent to yielding a list ofWait
objects.
4.0 版后已移除: UseFutures
instead.
- class
tornado.gen.
MultiYieldPoint
(children, quiet_exceptions=())[源代码]¶
Runs multiple asynchronous operations in parallel.
This class is similar tomulti
, but it always creates a stackcontext even when no children require it. It is not compatible withnative coroutines.
在 4.2 版更改: If multipleYieldPoints
fail, any exceptions after the first(which is raised) will be logged. Added thequiet_exceptions
argument to suppress this logging for selected exception types.
在 4.3 版更改: Renamed fromMulti
toMultiYieldPoint
. The nameMulti
remains as an alias for the equivalentmulti
function.
4.3 版后已移除: Usemulti
instead.
原文: