codekingpro/portable-devtools
114k
1# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
12"""Bridges between the Twisted package and Tornado."""
13
14import sys
15
16from twisted.internet.defer import Deferred # type: ignore
17from twisted.python import failure # type: ignore
18
19from tornado.concurrent import Future, future_set_exc_info
20from tornado import gen
21
22import typing # noqa: F401
23
24
25def install() -> None:
26 """Install ``AsyncioSelectorReactor`` as the default Twisted reactor.
27
28 .. deprecated:: 5.1
29
30 This function is provided for backwards compatibility; code
31 that does not require compatibility with older versions of
32 Tornado should use
33 ``twisted.internet.asyncioreactor.install()`` directly.
34
35 .. versionchanged:: 6.0.3
36
37 In Tornado 5.x and before, this function installed a reactor
38 based on the Tornado ``IOLoop``. When that reactor
39 implementation was removed in Tornado 6.0.0, this function was
40 removed as well. It was restored in Tornado 6.0.3 using the
41 ``asyncio`` reactor instead.
42
43 """
44 from twisted.internet.asyncioreactor import install # type: ignore
45
46 install()
47
48
49if hasattr(gen.convert_yielded, "register"):
50
51 @gen.convert_yielded.register(Deferred)
52 def _(d: Deferred) -> Future:
53 f = Future() # type: Future[typing.Any]
54
55 def errback(failure: failure.Failure) -> None:
56 try:
57 failure.raiseException()
58 # Should never happen, but just in case
59 raise Exception("errback called without error")
60 except:
61 future_set_exc_info(f, sys.exc_info())
62
63 d.addCallbacks(f.set_result, errback)
64 return f
65 