What’s new in Tornado 4.2¶
May 26, 2015¶
Backwards-compatibility notes¶
SSLIOStream.connectandIOStream.start_tlsnow validate certificates by default.- Certificate validation will now use the system CA root certificates instead
of
certifiwhen possible (i.e. Python 2.7.9+ or 3.4+). This includesIOStreamandsimple_httpclient, but notcurl_httpclient. - The default SSL configuration has become stricter, using
ssl.create_default_contextwhere available on the client side. (On the server side, applications are encouraged to migrate from thessl_optionsdict-based API to pass anssl.SSLContextinstead). - The deprecated classes in the
tornado.authmodule,GoogleMixin,FacebookMixin, andFriendFeedMixinhave been removed.
New modules: tornado.locks and tornado.queues¶
These modules provide classes for coordinating coroutines, merged from Toro.
To port your code from Toro’s queues to Tornado 4.2, import Queue,
PriorityQueue, or LifoQueue from tornado.queues instead of from
toro.
Use Queue instead of Toro’s JoinableQueue. In Tornado the methods
join and task_done are available on all queues, not on a
special JoinableQueue.
Tornado queues raise exceptions specific to Tornado instead of reusing
exceptions from the Python standard library.
Therefore instead of catching the standard queue.Empty exception from
Queue.get_nowait, catch the special tornado.queues.QueueEmpty exception,
and instead of catching the standard queue.Full from Queue.get_nowait,
catch tornado.queues.QueueFull.
To port from Toro’s locks to Tornado 4.2, import Condition, Event,
Semaphore, BoundedSemaphore, or Lock from tornado.locks
instead of from toro.
Toro’s Semaphore.wait allowed a coroutine to wait for the semaphore to
be unlocked without acquiring it. This encouraged unorthodox patterns; in
Tornado, just use acquire.
Toro’s Event.wait raised a Timeout exception after a timeout. In
Tornado, Event.wait raises tornado.gen.TimeoutError.
Toro’s Condition.wait also raised Timeout, but in Tornado, the Future
returned by Condition.wait resolves to False after a timeout:
@gen.coroutine
def await_notification():
if not (yield condition.wait(timeout=timedelta(seconds=1))):
print('timed out')
else:
print('condition is true')
In lock and queue methods, wherever Toro accepted deadline as a keyword
argument, Tornado names the argument timeout instead.
Toro’s AsyncResult is not merged into Tornado, nor its exceptions
NotReady and AlreadySet. Use a Future instead. If you wrote code like
this:
from tornado import gen
import toro
result = toro.AsyncResult()
@gen.coroutine
def setter():
result.set(1)
@gen.coroutine
def getter():
value = yield result.get()
print(value) # Prints "1".
Then the Tornado equivalent is:
from tornado import gen
from tornado.concurrent import Future
result = Future()
@gen.coroutine
def setter():
result.set_result(1)
@gen.coroutine
def getter():
value = yield result
print(value) # Prints "1".
tornado.autoreload¶
- Improved compatibility with Windows.
- Fixed a bug in Python 3 if a module was imported during a reload check.
tornado.concurrent¶
run_on_executornow accepts arguments to control which attributes it uses to find theIOLoopand executor.
tornado.curl_httpclient¶
- Fixed a bug that would cause the client to stop processing requests if an exception occurred in certain places while there is a queue.
tornado.escape¶
xhtml_escapenow supports numeric character references in hex format ( )
tornado.gen¶
WaitIteratorno longer uses weak references, which fixes several garbage-collection-related bugs.tornado.gen.Multiandtornado.gen.multi_future(which are used when yielding a list or dict in a coroutine) now log any exceptions after the first if more than oneFuturefails (previously they would be logged when theFuturewas garbage-collected, but this is more reliable). Both have a new keyword argumentquiet_exceptionsto suppress logging of certain exception types; to use this argument you must callMultiormulti_futuredirectly instead of simply yielding a list.multi_futurenow works when given multiple copies of the sameFuture.- On Python 3, catching an exception in a coroutine no longer leads to
leaks via
Exception.__context__.
tornado.httpclient¶
- The
raise_errorargument now works correctly with the synchronousHTTPClient. - The synchronous
HTTPClientno longer interferes withIOLoop.current().
tornado.httpserver¶
HTTPServeris now a subclass oftornado.util.Configurable.
tornado.httputil¶
HTTPHeaderscan now be copied withcopy.copyandcopy.deepcopy.
tornado.ioloop¶
- The
IOLoopconstructor now has amake_currentkeyword argument to control whether the newIOLoopbecomesIOLoop.current(). - Third-party implementations of
IOLoopshould accept**kwargsin theirinitializemethods and pass them to the superclass implementation. PeriodicCallbackis now more efficient when the clock jumps forward by a large amount.
tornado.iostream¶
SSLIOStream.connectandIOStream.start_tlsnow validate certificates by default.- New method
SSLIOStream.wait_for_handshakeallows server-side applications to wait for the handshake to complete in order to verify client certificates or use NPN/ALPN. - The
Futurereturned bySSLIOStream.connectnow resolves after the handshake is complete instead of as soon as the TCP connection is established. - Reduced logging of SSL errors.
BaseIOStream.read_until_closenow works correctly when astreaming_callbackis given butcallbackis None (i.e. when it returns aFuture)
tornado.locale¶
- New method
GettextLocale.pgettextallows additional context to be supplied for gettext translations.
tornado.log¶
define_logging_optionsnow works correctly when given a non-defaultoptionsobject.
tornado.process¶
- New method
Subprocess.wait_for_exitis a coroutine-friendly version ofSubprocess.set_exit_callback.
tornado.simple_httpclient¶
- Improved performance on Python 3 by reusing a single
ssl.SSLContext. - New constructor argument
max_body_sizecontrols the maximum response size the client is willing to accept. It may be bigger thanmax_buffer_sizeifstreaming_callbackis used.
tornado.tcpserver¶
TCPServer.handle_streammay be a coroutine (so that any exceptions it raises will be logged).
tornado.util¶
import_objectnow supports unicode strings on Python 2.Configurable.initializenow supports positional arguments.
tornado.web¶
- Key versioning support for cookie signing.
cookie_secretapplication setting can now contain a dict of valid keys with version as key. The current signing key then must be specified viakey_versionsetting. - Parsing of the
If-None-Matchheader now follows the RFC and supports weak validators. - Passing
secure=Falseorhttponly=FalsetoRequestHandler.set_cookienow works as expected (previously only the presence of the argument was considered and its value was ignored). RequestHandler.get_argumentsnow requires that itsstripargument be of type bool. This helps prevent errors caused by the slightly dissimilar interfaces between the singular and plural methods.- Errors raised in
_handle_request_exceptionare now logged more reliably. RequestHandler.redirectnow works correctly when called from a handler whose path begins with two slashes.- Passing messages containing
%characters totornado.web.HTTPErrorno longer causes broken error messages.
tornado.websocket¶
- The
on_closemethod will no longer be called more than once. - When the other side closes a connection, we now echo the received close code back instead of sending an empty close frame.