本文整理汇总了Python中txaio.use_asyncio函数的典型用法代码示例。如果您正苦于以下问题:Python use_asyncio函数的具体用法?Python use_asyncio怎么用?Python use_asyncio使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了use_asyncio函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_use_asyncio
def test_use_asyncio(framework_aio):
pytest.importorskip('asyncio')
import txaio
txaio.use_asyncio()
assert txaio.using_asyncio
assert not txaio.using_twisted
示例2: run
def run(self, make):
"""
Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
"""
# 1) factory for use ApplicationSession
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception as e:
# the app component could not be created .. fatal
print(e)
asyncio.get_event_loop().stop()
else:
session.debug_app = self.debug_app
return session
isSecure, host, port, resource, path, params = parseWsUrl(self.url)
if self.ssl is None:
ssl = isSecure
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)
loop.add_signal_handler(signal.SIGTERM, loop.stop)
# 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
# give Goodbye message a chance to go through, if we still
# have an active session
if protocol._session:
loop.run_until_complete(protocol._session.leave())
loop.close()
示例3: __init__
def __init__(self, handler, proto_id, auth_strategy, loop):
txaio.use_asyncio()
websocket.WebSocketServerProtocol.__init__(self)
self._handler = handler
self.proto_id = proto_id
self._auth_strategy = auth_strategy
self._loop = loop
self._authentified = False
self._auth_app = None
self._deauth_handle = None
示例4: run
def run(self, make):
"""
Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
"""
# 1) factory for use ApplicationSession
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception as e:
# the app component could not be created .. fatal
print(e)
asyncio.get_event_loop().stop()
else:
session.debug_app = self.debug_app
return session
isSecure, host, port, resource, path, params = parseWsUrl(self.url)
if self.ssl is None:
ssl = isSecure
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)
loop.run_until_complete(coro)
# 4) now enter the asyncio event loop
loop.run_forever()
loop.close()
示例5: run
def run(self, make):
"""
Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
"""
def _create_app_session():
cfg = ComponentConfig(self._realm, self._extra)
try:
session = make(cfg)
except Exception as e:
# the app component could not be created .. fatal
asyncio.get_event_loop().stop()
raise e
else:
session.debug_app = self._debug_app
return session
self._transport_factory = WampWebSocketClientFactory(_create_app_session, url=self._url, serializers=self._serializers)
if self._auto_ping_interval is not None and self._auto_ping_timeout is not None:
self._transport_factory.setProtocolOptions(autoPingInterval=self._auto_ping_interval, autoPingTimeout=self._auto_ping_timeout)
txaio.use_asyncio()
txaio.config.loop = self._loop
asyncio.async(self._connect(), loop=self._loop)
self._loop.add_signal_handler(signal.SIGTERM, self.stop)
try:
self._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
self._closing = True
if self._active_protocol and self._active_protocol._session:
self._loop.run_until_complete(self._active_protocol._session.leave())
self._loop.close()
示例6: start
async def start(self, ctx: Context):
# Autobahn uses txaio to bridge the API gap between asyncio and Twisted so we need to set
# it up for asyncio here
txaio.use_asyncio()
txaio.config.loop = ctx.loop
ctx.add_resource(WAMPExtrasProvider(), 'wamp', types=[ExtrasProvider])
for resource_name, context_attr, client in self.clients:
await client.start(ctx)
ctx.add_resource(client, resource_name, context_attr)
logger.info('Configured WAMP client (%s / ctx.%s; host=%s; port=%d; realm=%s)',
resource_name, context_attr, client.host, client.port, client.realm)
await yield_()
for resource_name, context_attr, client in self.clients:
await client.stop()
logger.info('Shut down WAMP client (%s)', resource_name)
示例7: run
def run(self, make):
"""
Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
"""
# 1) factory for use ApplicationSession
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception as e:
# the app component could not be created .. fatal
print(e)
get_event_loop().stop()
else:
session.debug_app = self.debug_app
return session
isSecure, host, port, resource, path, params = parseWsUrl(self.url)
# 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 = get_event_loop()
txaio.use_asyncio()
txaio.config.loop = loop
coro = loop.create_connection(transport_factory, host, port, ssl=isSecure)
loop.run_until_complete(coro)
# 4) now enter the asyncio event loop
loop.run_forever()
loop.close()
示例8: ApplicationSession
import six
from autobahn.wamp import protocol
from autobahn.wamp.types import ComponentConfig
from autobahn.websocket.util import parse_url
from autobahn.asyncio.websocket import WampWebSocketClientFactory
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed to asyncio
# noinspection PyUnresolvedReferences
import trollius as asyncio
import txaio
txaio.use_asyncio()
__all__ = (
'ApplicationSession',
'ApplicationSessionFactory',
'ApplicationRunner'
)
class ApplicationSession(protocol.ApplicationSession):
"""
WAMP application session for asyncio-based applications.
"""
class ApplicationSessionFactory(protocol.ApplicationSessionFactory):
示例9: run
def run(self, make, start_loop=True, log_level='info'):
"""
Run the application component. Under the hood, this runs the event
loop (unless `start_loop=False` is passed) so won't return
until the program is done.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
:param start_loop: When ``True`` (the default) this method
start a new asyncio loop.
:type start_loop: bool
:returns: None is returned, unless you specify
`start_loop=False` in which case the coroutine from calling
`loop.create_connection()` is returned. This will yield the
(transport, protocol) pair.
"""
if callable(make):
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception as e:
self.log.error('ApplicationSession could not be instantiated: {}'.format(e))
loop = asyncio.get_event_loop()
if loop.is_running():
loop.stop()
raise
else:
return session
else:
create = make
if self.url.startswith(u'rs'):
# try to parse RawSocket URL ..
isSecure, host, port = parse_rs_url(self.url)
# use the first configured serializer if any (which means, auto-choose "best")
serializer = self.serializers[0] if self.serializers else None
# create a WAMP-over-RawSocket transport client factory
transport_factory = WampRawSocketClientFactory(create, serializer=serializer)
else:
# try to parse WebSocket URL ..
isSecure, host, port, resource, path, params = parse_ws_url(self.url)
# create a WAMP-over-WebSocket transport client factory
transport_factory = WampWebSocketClientFactory(create, url=self.url, serializers=self.serializers, proxy=self.proxy, headers=self.headers)
# client WebSocket settings - similar to:
# - http://crossbar.io/docs/WebSocket-Compression/#production-settings
# - http://crossbar.io/docs/WebSocket-Options/#production-settings
# The permessage-deflate extensions offered to the server ..
offers = [PerMessageDeflateOffer()]
# Function to accept permessage_delate responses from the server ..
def accept(response):
if isinstance(response, PerMessageDeflateResponse):
return PerMessageDeflateResponseAccept(response)
# set WebSocket options for all client connections
transport_factory.setProtocolOptions(maxFramePayloadSize=1048576,
maxMessagePayloadSize=1048576,
autoFragmentSize=65536,
failByDrop=False,
openHandshakeTimeout=2.5,
closeHandshakeTimeout=1.,
tcpNoDelay=True,
autoPingInterval=10.,
autoPingTimeout=5.,
autoPingSize=4,
perMessageCompressionOffers=offers,
perMessageCompressionAccept=accept)
# SSL context for client connection
if self.ssl is None:
ssl = isSecure
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
# 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()
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
#.........这里部分代码省略.........
示例10:
###############################################################################
from __future__ import absolute_import
import signal
import six
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed to asyncio
# noinspection PyUnresolvedReferences
import trollius as asyncio
import txaio
txaio.use_asyncio() # noqa
from autobahn.util import public
from autobahn.wamp import protocol
from autobahn.wamp.types import ComponentConfig
from autobahn.websocket.util import parse_url as parse_ws_url
from autobahn.rawsocket.util import parse_url as parse_rs_url
from autobahn.asyncio.websocket import WampWebSocketClientFactory
from autobahn.asyncio.rawsocket import WampRawSocketClientFactory
from autobahn.websocket.compress import PerMessageDeflateOffer, \
PerMessageDeflateResponse, PerMessageDeflateResponseAccept
__all__ = (
示例11: setup_txaio
def setup_txaio(event_loop):
txaio.use_asyncio()
txaio.config.loop = event_loop
示例12: run
def run(self, make, logging_level='info'):
"""
Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable
"""
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception:
self.log.failure("App session could not be created! ")
asyncio.get_event_loop().stop()
else:
return session
parsed_url = urlparse(self.url)
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:
coro = loop.create_connection(transport_factory, parsed_url.hostname, parsed_url.port)
(_transport, protocol) = loop.run_until_complete(coro)
txaio.start_logging(level=logging_level) # @UndefinedVariable
try:
loop.run_forever()
except KeyboardInterrupt:
pass
self.log.debug('Left main loop waiting for completion')
# give Goodbye message a chance to go through, if we still
# have an active session
# it's not working now - because protocol is_closed must return Future
if protocol._session:
loop.run_until_complete(protocol._session.leave())
loop.close()