Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
one supplied temporarily. It's up to you to ensure you pass an
event_loop or a reactor instance depending upon asyncio/Twisted.
Use like so:
.. sourcecode:: python
from twisted.internet import task
with replace_loop(task.Clock()) as fake_reactor:
f = txaio.call_later(5, foo)
fake_reactor.advance(10)
# ...etc
"""
# setup
orig = txaio.config.loop
txaio.config.loop = new_loop
yield new_loop
# cleanup
txaio.config.loop = orig
:type start_loop: bool
:param log_level: a valid log-level (or None to avoid calling start_logging)
:type log_level: string
"""
# actually, should we even let people "not start" the logging? I'm
# not sure that's wise... (double-check: if they already called
# txaio.start_logging() what happens if we call it again?)
if log_level is not None:
txaio.start_logging(level=log_level)
loop = asyncio.get_event_loop()
if loop.is_closed():
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
txaio.config.loop = loop
log = txaio.make_logger()
# see https://github.com/python/asyncio/issues/341 asyncio has
# "odd" handling of KeyboardInterrupt when using Tasks (as
# run_until_complete does). Another option is to just resture
# default SIGINT handling, which is to exit:
# import signal
# signal.signal(signal.SIGINT, signal.SIG_DFL)
@asyncio.coroutine
def nicely_exit(signal):
log.info("Shutting down due to {signal}", signal=signal)
tasks = asyncio.Task.all_tasks()
for task in tasks:
# Do not cancel the current task.
"""
Function to get the websocket server going and run the event loop
that feeds it.
"""
# We need a new loop in case some other process has already started the
# main loop. In principle we might be able to do a check for a running
# loop but this works whether or not a loop is running.
__interact_loop = asyncio.new_event_loop()
# Need to do two things before starting the server factory:
#
# 1. Set our loop to be the default event loop on this thread
asyncio.set_event_loop(__interact_loop)
# 2. Line below is courtesy of
# https://github.com/crossbario/autobahn-python/issues/1007#issuecomment-391541322
txaio.config.loop = __interact_loop
# Now create the factory, start the server then run the event loop forever.
__factory = WebSocketServerFactory(u"ws://localhost:{}/".format(__SOCKET_PORT))
__factory.protocol = WSserver
__coro = __interact_loop.create_server(__factory, '0.0.0.0', __SOCKET_PORT)
__interact_loop.run_until_complete(__coro)
__interact_loop.run_forever()
else:
if self.ssl and not isSecure:
raise RuntimeError(
'ssl argument value passed to %s conflicts with the "ws:" '
'prefix of the url argument. Did you mean to use "wss:"?' %
self.__class__.__name__)
ssl = self.ssl
# 2) create a WAMP-over-WebSocket transport client factory
transport_factory = WampWebSocketClientFactory(create, url=self.url, serializers=self.serializers,
debug=self.debug, debug_wamp=self.debug_wamp)
# 3) start the client
loop = asyncio.get_event_loop()
txaio.use_asyncio()
txaio.config.loop = loop
coro = loop.create_connection(transport_factory, host, port, ssl=ssl)
(transport, protocol) = loop.run_until_complete(coro)
try:
loop.add_signal_handler(signal.SIGTERM, loop.stop)
except NotImplementedError:
# signals are not available on Windows
pass
# 4) now enter the asyncio event loop
try:
loop.run_forever()
except KeyboardInterrupt:
# wait until we send Goodbye if user hit ctrl-c
# (done outside this except so SIGTERM gets the same handling)
pass
if self.ssl and not isSecure:
raise RuntimeError(
'ssl argument value passed to %s conflicts with the "ws:" '
'prefix of the url argument. Did you mean to use "wss:"?' %
self.__class__.__name__)
ssl = self.ssl
# start the client connection
loop = asyncio.get_event_loop()
if loop.is_closed() and start_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
if hasattr(transport_factory, 'loop'):
transport_factory.loop = loop
txaio.use_asyncio()
txaio.config.loop = loop
coro = loop.create_connection(transport_factory, host, port, ssl=ssl)
# start a asyncio loop
if not start_loop:
return coro
else:
(transport, protocol) = loop.run_until_complete(coro)
# start logging
txaio.start_logging(level=log_level)
try:
loop.add_signal_handler(signal.SIGTERM, loop.stop)
except NotImplementedError:
# signals are not available on Windows
pass
def _consume(self):
self.waiter = Future(loop=self.factory.loop or txaio.config.loop)
def process(_):
while len(self.receive_queue):
data = self.receive_queue.popleft()
if self.transport:
self._dataReceived(data)
self._consume()
self.waiter.add_done_callback(process)
"{log_failure.getTraceback()"))
else:
log.debug("Running on Linux and optimal reactor (epoll) was installed.")
else:
log.debug("Running on Linux and optimal reactor (epoll) already installed.")
else:
try:
from twisted.internet import default as defaultreactor
defaultreactor.install()
except Exception:
log.failure(("Could not install default Twisted reactor for this platform"
"{log_failure.getTraceback()"))
from twisted.internet import reactor
txaio.config.loop = reactor
if parsed_url.scheme == 'tcp':
is_unix = False
if not parsed_url.hostname or not parsed_url.port:
raise ValueError('Host and port is required in URL')
elif parsed_url.scheme == 'unix' or parsed_url.scheme == '':
is_unix = True
if not parsed_url.path:
raise ValueError('Path to unix socket must be in URL')
transport_factory = WampRawSocketClientFactory(create, serializer=self.serializer)
loop = asyncio.get_event_loop()
if logging_level == 'debug':
loop.set_debug(True)
txaio.use_asyncio()
txaio.config.loop = loop
try:
loop.add_signal_handler(signal.SIGTERM, loop.stop)
except NotImplementedError:
# signals are not available on Windows
pass
def handle_error(loop, context):
self.log.error('Application Error: {err}', err=context)
loop.stop()
loop.set_exception_handler(handle_error)
if is_unix:
coro = loop.create_unix_connection(transport_factory, parsed_url.path)
else:
selectreactor.install()
# from twisted.internet import default as defaultreactor
# defaultreactor.install()
except:
log.warn('Running on "{platform}", but cannot install Select Twisted reactor: {tb}', tb=traceback.format_exc(), platform=sys.platform)
else:
log.debug('Running on "{platform}" and optimal reactor (Select) was installed.', platform=sys.platform)
else:
log.warn('Running on "{platform}", but cannot install Select Twisted reactor, because another reactor ({klass}) is already installed.', klass=current_reactor, platform=sys.platform)
if require_optimal_reactor:
raise ReactorAlreadyInstalledError()
else:
log.debug('Running on "{platform}" and optimal reactor (Select) already installed.', platform=sys.platform)
from twisted.internet import reactor
txaio.config.loop = reactor
return reactor
def run(self):
if six.PY2:
log.startLogging(sys.stdout)
reactor.listenTCP(self.config['port'], self)
reactor.run(installSignalHandlers=False)
else:
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
txaio.config.loop = self.loop
future = self.loop.create_server(self, self.config['host'], self.config['port'])
self.loop.run_until_complete(future)
self.loop.run_forever()