twisted.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import sys
  14. from twisted.internet.defer import Deferred # type: ignore
  15. from twisted.python import failure # type: ignore
  16. from tornado.concurrent import Future, future_set_exc_info
  17. from tornado import gen
  18. import typing # noqa: F401
  19. def install() -> None:
  20. """Install ``AsyncioSelectorReactor`` as the default Twisted reactor.
  21. .. deprecated:: 5.1
  22. This function is provided for backwards compatibility; code
  23. that does not require compatibility with older versions of
  24. Tornado should use
  25. ``twisted.internet.asyncioreactor.install()`` directly.
  26. .. versionchanged:: 6.0.3
  27. In Tornado 5.x and before, this function installed a reactor
  28. based on the Tornado ``IOLoop``. When that reactor
  29. implementation was removed in Tornado 6.0.0, this function was
  30. removed as well. It was restored in Tornado 6.0.3 using the
  31. ``asyncio`` reactor instead.
  32. """
  33. from twisted.internet.asyncioreactor import install # type: ignore
  34. install()
  35. if hasattr(gen.convert_yielded, "register"):
  36. @gen.convert_yielded.register(Deferred)
  37. def _(d: Deferred) -> Future:
  38. f = Future() # type: Future[typing.Any]
  39. def errback(failure: failure.Failure) -> None:
  40. try:
  41. failure.raiseException()
  42. # Should never happen, but just in case
  43. raise Exception("errback called without error")
  44. except:
  45. future_set_exc_info(f, sys.exc_info())
  46. d.addCallbacks(f.set_result, errback)
  47. return f