What’s new in Tornado 5.0
Mar 5, 2018
Highlights
The focus of this release is improving integration with
asyncio. On Python 3, theIOLoopis always a wrapper around theasyncioevent loop, andasyncio.Futureandasyncio.Taskare used instead of their Tornado counterparts. This means that libraries based onasynciocan be mixed relatively seamlessly with those using Tornado. While care has been taken to minimize the disruption from this change, code changes may be required for compatibility with Tornado 5.0, as detailed in the following section.Tornado 5.0 supports Python 2.7.9+ and 3.4+. Python 2.7 and 3.4 are deprecated and support for them will be removed in Tornado 6.0, which will require Python 3.5+.
Backwards-compatibility notes
Python 3.3 is no longer supported.
Versions of Python 2.7 that predate the
sslmodule update are no longer supported. (Thesslmodule was updated in version 2.7.9, although in some distributions the updates are present in builds with a lower version number. Tornado requiresssl.SSLContext,ssl.create_default_context, andssl.match_hostname)Versions of Python 3.5 prior to 3.5.2 are no longer supported due to a change in the async iterator protocol in that version.
The
trolliusproject (asynciobackported to Python 2) is no longer supported.tornado.concurrent.Futureis now an alias forasyncio.Futurewhen running on Python 3. This results in a number of minor behavioral changes:Futureobjects can only be created while there is a currentIOLoopThe timing of callbacks scheduled with
Future.add_done_callbackhas changed.tornado.concurrent.future_add_done_callbackcan be used to make the behavior more like older versions of Tornado (but not identical). Some of these changes are also present in the Python 2 version oftornado.concurrent.Futureto minimize the difference between Python 2 and 3.Cancellation is now partially supported, via
asyncio.Future.cancel. A canceledFuturecan no longer have its result set. Applications that handleFutureobjects directly may want to usetornado.concurrent.future_set_result_unless_cancelled. In native coroutines, cancellation will cause an exception to be raised in the coroutine.The
exc_infoandset_exc_infomethods are no longer present. Usetornado.concurrent.future_set_exc_infoto replace the latter, and raise the exception withresultto replace the former.
io_looparguments to many Tornado functions have been removed. UseIOLoop.current()instead of passingIOLoopobjects explicitly.On Python 3,
IOLoopis always a wrapper around theasyncioevent loop.IOLoop.configureis effectively removed on Python 3 (for compatibility, it may be called to redundantly specify theasyncio-backedIOLoop)IOLoop.instanceis now a deprecated alias forIOLoop.current. Applications that need the cross-thread communication behavior facilitated byIOLoop.instanceshould use their own global variable instead.
Other notes
The
futures(concurrent.futuresbackport) package is now required on Python 2.7.The
certifiandbackports.ssl-match-hostnamepackages are no longer required on Python 2.7.Python 3.6 or higher is recommended, because it features more efficient garbage collection of
asyncio.Futureobjects.
tornado.auth
GoogleOAuth2Mixinnow uses a newer set of URLs.
tornado.autoreload
On Python 3, uses
__main__.__specto more reliably reconstruct the original command line and avoid modifyingPYTHONPATH.The
io_loopargument totornado.autoreload.starthas been removed.
tornado.concurrent
tornado.concurrent.Futureis now an alias forasyncio.Futurewhen running on Python 3. See “Backwards-compatibility notes” for more.Setting the result of a
Futureno longer blocks while callbacks are being run. Instead, the callbacks are scheduled on the nextIOLoopiteration.The deprecated alias
tornado.concurrent.TracebackFuturehas been removed.tornado.concurrent.chain_futurenow works with all three kinds ofFutures(Tornado,asyncio, andconcurrent.futures)The
io_loopargument totornado.concurrent.run_on_executorhas been removed.New functions
future_set_result_unless_cancelled,future_set_exc_info, andfuture_add_done_callbackhelp mask the difference betweenasyncio.Futureand Tornado’s previousFutureimplementation.
tornado.curl_httpclient
Improved debug logging on Python 3.
The
time_inforesponse attribute now includesappconnectin addition to other measurements.Closing a
CurlAsyncHTTPClientnow breaks circular references that could delay garbage collection.The
io_loopargument to theCurlAsyncHTTPClientconstructor has been removed.
tornado.gen
tornado.gen.TimeoutErroris now an alias fortornado.util.TimeoutError.Leak detection for
Futurescreated by this module now attributes them to their proper caller instead of the coroutine machinery.Several circular references that could delay garbage collection have been broken up.
On Python 3,
asyncio.Taskis used instead of the Tornado coroutine runner. This improves compatibility with someasynciolibraries and adds support for cancellation.The
io_looparguments toYieldFutureandwith_timeouthave been removed.
tornado.httpclient
The
io_loopargument to allAsyncHTTPClientconstructors has been removed.
tornado.httpserver
It is now possible for a client to reuse a connection after sending a chunked request.
If a client sends a malformed request, the server now responds with a 400 error instead of simply closing the connection.
Content-LengthandTransfer-Encodingheaders are no longer sent with 1xx or 204 responses (this was already true of 304 responses).When closing a connection to a HTTP/1.1 client, the
Connection: closeheader is sent with the response.The
io_loopargument to theHTTPServerconstructor has been removed.If more than one
X-SchemeorX-Forwarded-Protoheader is present, only the last is used.
tornado.httputil
The string representation of
HTTPServerRequestobjects (which are sometimes used in log messages) no longer includes the request headers.New function
qs_to_qslconverts the result ofurllib.parse.parse_qsto name-value pairs.
tornado.ioloop
tornado.ioloop.TimeoutErroris now an alias fortornado.util.TimeoutError.IOLoop.instanceis now a deprecated alias forIOLoop.current.IOLoop.installandIOLoop.clear_instanceare deprecated.The
IOLoop.initializedmethod has been removed.On Python 3, the
asyncio-backedIOLoopis always used and alternativeIOLoopimplementations cannot be configured.IOLoop.currentand related methods pass through toasyncio.get_event_loop.run_synccancels its argument on a timeout. This results in better stack traces (and avoids log messages about leaks) in native coroutines.New methods
IOLoop.run_in_executorandIOLoop.set_default_executormake it easier to run functions in other threads from native coroutines (sinceconcurrent.futures.Futuredoes not supportawait).PollIOLoop(the default on Python 2) attempts to detect misuse ofIOLoopinstances acrossos.fork.The
io_loopargument toPeriodicCallbackhas been removed.It is now possible to create a
PeriodicCallbackin one thread and start it in another without passing an explicit event loop.The
IOLoop.set_blocking_signal_thresholdandIOLoop.set_blocking_log_thresholdmethods are deprecated because they are not implemented for theasyncioevent loop`. Use thePYTHONASYNCIODEBUG=1environment variable instead.IOLoop.clear_currentnow works if it is called before any current loop is established.
tornado.iostream
The
io_loopargument to theIOStreamconstructor has been removed.New method
BaseIOStream.read_intoprovides a minimal-copy alternative toBaseIOStream.read_bytes.BaseIOStream.writeis now much more efficient for very large amounts of data.Fixed some cases in which
IOStream.errorcould be inaccurate.Writing a
memoryviewcan no longer result in “BufferError: Existing exports of data: object cannot be re-sized”.
tornado.locks
As a side effect of the
Futurechanges, waiters are always notified asynchronously with respect toCondition.notify.
tornado.netutil
The default
Resolvernow usesIOLoop.run_in_executor.ExecutorResolver,BlockingResolver, andThreadedResolverare deprecated.The
io_looparguments toadd_accept_handler,ExecutorResolver, andThreadedResolverhave been removed.add_accept_handlerreturns a callable which can be used to remove all handlers that were added.OverrideResolvernow accepts per-family overrides.
tornado.options
Duplicate option names are now detected properly whether they use hyphens or underscores.
tornado.platform.asyncio
AsyncIOLoopandAsyncIOMainLoopare now used automatically when appropriate; referencing them explicitly is no longer recommended.Starting an
IOLoopor making it current now also sets theasyncioevent loop for the current thread. Closing anIOLoopcloses the correspondingasyncioevent loop.to_tornado_futureandto_asyncio_futureare deprecated since they are now no-ops.AnyThreadEventLoopPolicycan now be used to easily allow the creation of event loops on any thread (similar to Tornado’s prior policy).
tornado.platform.caresresolver
The
io_loopargument toCaresResolverhas been removed.
tornado.platform.twisted
The
io_looparguments toTornadoReactor,TwistedResolver, andtornado.platform.twisted.installhave been removed.
tornado.process
The
io_loopargument to theSubprocessconstructor andSubprocess.initializehas been removed.
tornado.routing
A default 404 response is now generated if no delegate is found for a request.
tornado.simple_httpclient
The
io_loopargument toSimpleAsyncHTTPClienthas been removed.TLS is now configured according to
ssl.create_default_contextby default.
tornado.tcpclient
The
io_loopargument to theTCPClientconstructor has been removed.TCPClient.connecthas a newtimeoutargument.
tornado.tcpserver
tornado.testing
The deprecated
tornado.testing.get_unused_portandtornado.testing.LogTrapTestCasehave been removed.AsyncHTTPTestCase.fetchnow supports absolute URLs.AsyncHTTPTestCase.fetchnow connects to127.0.0.1instead oflocalhostto be more robust against faulty ipv6 configurations.
tornado.util
tornado.util.TimeoutErrorreplacestornado.gen.TimeoutErrorandtornado.ioloop.TimeoutError.Configurablenow supports configuration at multiple levels of an inheritance hierarchy.
tornado.web
RequestHandler.set_statusno longer requires that the given status code appear inhttp.client.responses.It is no longer allowed to send a body with 1xx or 204 responses.
Exception handling now breaks up reference cycles that could delay garbage collection.
RedirectHandlernow copies any query arguments from the request to the redirect location.If both
If-None-MatchandIf-Modified-Sinceheaders are present in a request toStaticFileHandler, the latter is now ignored.
tornado.websocket
The C accelerator now operates on multiple bytes at a time to improve performance.
Requests with invalid websocket headers now get a response with status code 400 instead of a closed connection.
WebSocketHandler.write_messagenow raisesWebSocketClosedErrorif the connection closes while the write is in progress.The
io_loopargument towebsocket_connecthas been removed.