desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
':param url: Raw socket unicode - either path on local server to unix socket (or unix:/path)
or tcp://host:port for internet socket
:type url: unicode
:param realm: The WAMP realm to join the application session to.
:type realm: unicode
:param extra: Optional extra configuration to forward to the application component.... | def __init__(self, url, realm, extra=None, serializer=None):
| assert (type(url) == six.text_type)
assert (type(realm) == six.text_type)
assert ((extra is None) or (type(extra) == dict))
self.url = url
self.realm = realm
self.extra = (extra or dict())
self.serializer = serializer
|
'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 run(self, make, logging_level='info'):
| 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
par... |
':param all_done: Deferred that gets callback() when our process exits (.errback if it exits non-zero)
:param launched: Deferred that gets callback() when our process starts.'
| def __init__(self, all_done, launched, color=None, prefix=''):
| self.all_done = all_done
self.launched = launched
self.color = (color or '')
self.prefix = prefix
self._out = ''
self._err = ''
|
'ProcessProtocol override'
| def connectionMade(self):
| if (not self.launched.called):
self.launched.callback(self)
|
'ProcessProtocol override'
| def outReceived(self, data):
| self._out += data.decode('utf8')
while ('\n' in self._out):
idx = self._out.find('\n')
line = self._out[:idx]
self._out = self._out[(idx + 1):]
sys.stdout.write(((((self.prefix + self.color) + line) + Fore.RESET) + '\n'))
|
'ProcessProtocol override'
| def errReceived(self, data):
| self._err += data.decode('utf8')
while ('\n' in self._err):
idx = self._err.find('\n')
line = self._err[:idx]
self._err = self._err[(idx + 1):]
sys.stderr.write(((((self.prefix + self.color) + line) + Fore.RESET) + '\n'))
|
'IProcessProtocol API'
| def processEnded(self, reason):
| fail = reason.value
if ((fail.exitCode != 0) and (fail.exitCode is not None)):
msg = 'Process exited with code "{}".'.format(fail.exitCode)
err = RuntimeError(msg)
self.all_done.errback(err)
if (not self.launched.called):
self.launched.errback(err)
els... |
'Constructor.
:param serializer: The object serializer to use for WAMP wire-level serialization.
:type serializer: An object that implements :class:`autobahn.interfaces.IObjectSerializer`.'
| def __init__(self, serializer):
| self._serializer = serializer
|
'Implements :func:`autobahn.wamp.interfaces.ISerializer.serialize`'
| def serialize(self, msg):
| return (msg.serialize(self._serializer), self._serializer.BINARY)
|
'Implements :func:`autobahn.wamp.interfaces.ISerializer.unserialize`'
| def unserialize(self, payload, isBinary=None):
| if (isBinary is not None):
if (isBinary != self._serializer.BINARY):
raise ProtocolError('invalid serialization of WAMP message (binary {0}, but expected {1})'.format(isBinary, self._serializer.BINARY))
try:
raw_msgs = self._serializer.unserialize(payload)
... |
'Ctor.
:param batched: Flag that controls whether serializer operates in batched mode.
:type batched: bool'
| def __init__(self, batched=False):
| self._batched = batched
|
'Implements :func:`autobahn.wamp.interfaces.IObjectSerializer.serialize`'
| def serialize(self, obj):
| s = _dumps(obj)
if isinstance(s, six.text_type):
s = s.encode('utf8')
if self._batched:
return (s + '\x18')
else:
return s
|
'Implements :func:`autobahn.wamp.interfaces.IObjectSerializer.unserialize`'
| def unserialize(self, payload):
| if self._batched:
chunks = payload.split('\x18')[:(-1)]
else:
chunks = [payload]
if (len(chunks) == 0):
raise Exception('batch format error')
return [_loads(data.decode('utf8')) for data in chunks]
|
'Ctor.
:param batched: Flag to control whether to put this serialized into batched mode.
:type batched: bool'
| def __init__(self, batched=False):
| Serializer.__init__(self, JsonObjectSerializer(batched=batched))
if batched:
self.SERIALIZER_ID = u'json.batched'
|
':param error: The URI of the error that occurred, e.g. ``wamp.error.not_authorized``.
:type error: str'
| def __init__(self, error, *args, **kwargs):
| Exception.__init__(self, *args)
self.kwargs = kwargs
self.error = error
self.enc_algo = kwargs.pop('enc_algo', None)
|
'Get the error message of this exception.
:returns: The error message.
:rtype: str'
| @public
def error_message(self):
| return u'{0}: {1}'.format(self.error, u' '.join([six.text_type(a) for a in self.args]))
|
''
| def __init__(self, idx, kind, url, endpoint, serializers, max_retries=15, max_retry_delay=300, initial_retry_delay=1.5, retry_delay_growth=1.5, retry_delay_jitter=0.1, options=dict()):
| self.idx = idx
self.type = kind
self.url = url
self.endpoint = endpoint
self.options = options
self.serializers = serializers
if ((self.type == 'rawsocket') and (len(serializers) != 1)):
raise ValueError("'rawsocket' transport requires exactly one serializer")
self... |
'set connection failure rates and retry-delay to initial values'
| def reset(self):
| self.connect_attempts = 0
self.connect_sucesses = 0
self.connect_failures = 0
self.retry_delay = self.initial_retry_delay
|
'Mark this transport as failed, meaning we won\'t try to connect to
it any longer (that is: can_reconnect() will always return
False afer calling this).'
| def failed(self):
| self._permanent_failure = True
|
'returns a human-readable description of the endpoint'
| def describe_endpoint(self):
| if isinstance(self.endpoint, dict):
return self.endpoint['type']
return repr(self.endpoint)
|
'A decorator as a shortcut for subscribing during on-join
For example::
@component.subscribe(
u"some.topic",
options=SubscribeOptions(match=u\'prefix\'),
def topic(*args, **kw):
print("some.topic({}, {}): event received".format(args, kw))'
| def subscribe(self, topic, options=None):
| assert ((options is None) or isinstance(options, SubscribeOptions))
def decorator(fn):
def do_subscription(session, details):
return session.subscribe(fn, topic=topic, options=options)
self.on('join', do_subscription)
return decorator
|
'A decorator as a shortcut for registering during on-join
For example::
@component.register(
u"com.example.add",
options=RegisterOptions(invoke=\'round_robin\'),
def add(*args, **kw):
print("add({}, {}): event received".format(args, kw))'
| def register(self, uri, options=None):
| assert ((options is None) or isinstance(options, RegisterOptions))
def decorator(fn):
def do_registration(session, details):
return session.register(fn, procedure=uri, options=options)
self.on('join', do_registration)
return decorator
|
':param main: After a transport has been connected and a session
has been established and joined to a realm, this (async)
procedure will be run until it finishes -- which signals that
the component has run to completion. In this case, it usually
doesn\'t make sense to use the ``on_*`` kwargs. If you do not
pass a main(... | def __init__(self, main=None, transports=None, config=None, realm=u'default', extra=None, authentication=None):
| self.set_valid_events(['start', 'connect', 'join', 'ready', 'leave', 'disconnect'])
if ((main is not None) and (not callable(main))):
raise RuntimeError('"main" must be a callable if given')
self._entry = main
if (transports is None):
transports = u'ws://127.0.0.1:8080/... |
'A decorator as a shortcut for listening for \'join\' events.
For example::
@component.on_join
def joined(session, details):
print("Session {} joined: {}".format(session, details))'
| def on_join(self, fn):
| self.on('join', fn)
|
'A decorator as a shortcut for listening for \'leave\' events.'
| def on_leave(self, fn):
| self.on('leave', fn)
|
'A decorator as a shortcut for listening for \'connect\' events.'
| def on_connect(self, fn):
| self.on('connect', fn)
|
'A decorator as a shortcut for listening for \'disconnect\' events.'
| def on_disconnect(self, fn):
| self.on('disconnect', fn)
|
'A decorator as a shortcut for listening for \'ready\' events.'
| def on_ready(self, fn):
| self.on('ready', fn)
|
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onOpen`'
| def onOpen(self):
| try:
self._session = self.factory._factory()
self._session.onOpen(self)
except Exception as e:
self.log.critical('{tb}', tb=traceback.format_exc())
reason = u'WAMP Internal Error ({0})'.format(e)
self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INTERNAL... |
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onClose`'
| def onClose(self, wasClean, code, reason):
| if (self._session is not None):
try:
self.log.debug('WAMP-over-WebSocket transport lost: wasClean={wasClean}, code={code}, reason="{reason}"', wasClean=wasClean, code=code, reason=reason)
self._session.onClose(wasClean)
except Exception:
self.log.cr... |
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessage`'
| def onMessage(self, payload, isBinary):
| try:
for msg in self._serializer.unserialize(payload, isBinary):
self.log.trace('WAMP RECV: message={message}, session={session}, authid={authid}', authid=self._session._authid, session=self._session._session_id, message=msg)
self._session.onMessage(msg)
except Protoc... |
'Implements :func:`autobahn.wamp.interfaces.ITransport.send`'
| def send(self, msg):
| if self.isOpen():
try:
self.log.trace('WAMP SEND: message={message}, session={session}, authid={authid}', authid=self._session._authid, session=self._session._session_id, message=msg)
(payload, isBinary) = self._serializer.serialize(msg)
except Exception as e:
... |
'Implements :func:`autobahn.wamp.interfaces.ITransport.isOpen`'
| def isOpen(self):
| return (self._session is not None)
|
'Implements :func:`autobahn.wamp.interfaces.ITransport.close`'
| def close(self):
| if self.isOpen():
self.sendClose(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL)
else:
raise TransportLost()
|
'Implements :func:`autobahn.wamp.interfaces.ITransport.abort`'
| def abort(self):
| if self.isOpen():
self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_GOING_AWAY)
else:
raise TransportLost()
|
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onConnect`'
| def onConnect(self, request):
| headers = {}
for subprotocol in request.protocols:
(version, serializerId) = parseSubprotocolIdentifier(subprotocol)
if ((version == 2) and (serializerId in self.factory._serializers.keys())):
self._serializer = self.factory._serializers[serializerId]
return (subprotocol,... |
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onConnect`'
| def onConnect(self, response):
| if (response.protocol not in self.factory.protocols):
if self.STRICT_PROTOCOL_NEGOTIATION:
raise Exception(u'The server does not speak any of the WebSocket subprotocols {} we requested.'.format(u', '.join(self.factory.protocols)))
else:
... |
'Ctor.
:param factory: A callable that produces instances that implement
:class:`autobahn.wamp.interfaces.ITransportHandler`
:type factory: callable
:param serializers: A list of WAMP serializers to use (or None for default
serializers). Serializers must implement
:class:`autobahn.wamp.interfaces.ISerializer`.
:type se... | def __init__(self, factory, serializers=None):
| if callable(factory):
self._factory = factory
else:
self._factory = (lambda : factory)
if (serializers is None):
serializers = []
try:
from autobahn.wamp.serializer import CBORSerializer
serializers.append(CBORSerializer(batched=True))
seri... |
''
| def __init__(self):
| self.set_valid_events(valid_events=['join', 'leave', 'ready', 'connect', 'disconnect'])
self.traceback_app = False
self._ecls_to_uri_pat = {}
self._uri_to_ecls = {ApplicationError.INVALID_PAYLOAD: SerializationError}
self._authid = None
self._authrole = None
self._authmethod = None
self.... |
'Implements :func:`autobahn.wamp.interfaces.ISession.define`'
| def define(self, exception, error=None):
| if (error is None):
assert hasattr(exception, '_wampuris')
self._ecls_to_uri_pat[exception] = exception._wampuris
self._uri_to_ecls[exception._wampuris[0].uri()] = exception
else:
assert (not hasattr(exception, '_wampuris'))
self._ecls_to_uri_pat[exception] = [uri.Pattern... |
'Create a WAMP error message from an exception.
:param request_type: The request type this WAMP error message is for.
:type request_type: int
:param request: The request ID this WAMP error message is for.
:type request: int
:param exc: The exception.
:type exc: Instance of :class:`Exception` or subclass thereof.
:param... | def _message_from_exception(self, request_type, request, exc, tb=None, enc_algo=None):
| args = None
if hasattr(exc, 'args'):
args = list(exc.args)
kwargs = None
if hasattr(exc, 'kwargs'):
kwargs = exc.kwargs
if tb:
if kwargs:
kwargs['traceback'] = tb
else:
kwargs = {'traceback': tb}
if isinstance(exc, exception.ApplicationErro... |
'Create a user (or generic) exception from a WAMP error message.
:param msg: A WAMP error message.
:type msg: instance of :class:`autobahn.wamp.message.Error`'
| def _exception_from_message(self, msg):
| exc = None
enc_err = None
if msg.enc_algo:
if (not self._payload_codec):
log_msg = u'received encoded payload, but no payload codec active'
self.log.warn(log_msg)
enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg, enc_a... |
'Implements :func:`autobahn.wamp.interfaces.ISession`'
| def __init__(self, config=None):
| BaseSession.__init__(self)
self.config = (config or types.ComponentConfig(realm=u'default'))
self._transport = None
self._session_id = None
self._realm = None
self._goodbye_sent = False
self._transport_is_closing = False
self._publish_reqs = {}
self._subscribe_reqs = {}
self._uns... |
'Implements :func:`autobahn.wamp.interfaces.ISession.set_payload_codec`'
| @public
def set_payload_codec(self, payload_codec):
| assert ((payload_codec is None) or isinstance(payload_codec, IPayloadCodec))
self._payload_codec = payload_codec
|
'Implements :func:`autobahn.wamp.interfaces.ISession.get_payload_codec`'
| @public
def get_payload_codec(self):
| return self._payload_codec
|
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen`'
| @public
def onOpen(self, transport):
| self._transport = transport
d = self.fire('connect', self, transport)
txaio.add_callbacks(d, None, (lambda fail: self._swallow_error(fail, "While notifying 'connect'")))
txaio.add_callbacks(d, (lambda _: txaio.as_future(self.onConnect)), None)
|
'Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`'
| @public
def onConnect(self):
| self.join(self.config.realm)
|
'Implements :func:`autobahn.wamp.interfaces.ISession.join`'
| @public
def join(self, realm, authmethods=None, authid=None, authrole=None, authextra=None, resumable=None, resume_session=None, resume_token=None):
| assert ((realm is None) or (type(realm) == six.text_type))
assert ((authmethods is None) or (type(authmethods) == list))
if (type(authmethods) == list):
for authmethod in authmethods:
assert (type(authmethod) == six.text_type)
assert ((authid is None) or (type(authid) == six.text_typ... |
'Implements :func:`autobahn.wamp.interfaces.ISession.disconnect`'
| @public
def disconnect(self):
| if self._transport:
self._transport.close()
|
'Implements :func:`autobahn.wamp.interfaces.ISession.is_connected`'
| @public
def is_connected(self):
| return (self._transport is not None)
|
'Implements :func:`autobahn.wamp.interfaces.ISession.is_attached`'
| @public
def is_attached(self):
| return ((self._transport is not None) and (self._session_id is not None))
|
'Implements :func:`autobahn.wamp.interfaces.ISession.onUserError`'
| @public
def onUserError(self, fail, msg):
| if (False and isinstance(fail.value, exception.ApplicationError)):
self.log.error(fail.value.error_message())
else:
self.log.error(u'{msg}: {traceback}', msg=msg, traceback=txaio.failure_format_traceback(fail))
|
'This is an internal generic error-handler for errors encountered
when calling down to on*() handlers that can reasonably be
expected to be overridden in user code.
Note that it *cancels* the error, so use with care!
Specifically, this should *never* be added to the errback
chain for a Deferred/coroutine that will make... | def _swallow_error(self, fail, msg):
| try:
self.onUserError(fail, msg)
except Exception:
self.log.error('Internal error: {tb}', tb=txaio.failure_format_traceback(txaio.create_failure()))
return None
|
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onMessage`'
| def onMessage(self, msg):
| if (self._session_id is None):
if isinstance(msg, message.Welcome):
if msg.realm:
self._realm = msg.realm
self._session_id = msg.session
self._router_roles = msg.roles
details = SessionDetails(realm=self._realm, session=self._session_id, authid... |
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onClose`'
| @public
def onClose(self, wasClean):
| self._transport = None
if self._session_id:
details = types.CloseDetails(reason=types.CloseDetails.REASON_TRANSPORT_LOST, message=u'WAMP transport was lost without closing the session before')
d = txaio.as_future(self.onLeave, details)
def success(arg):
... |
'Implements :func:`autobahn.wamp.interfaces.ISession.onChallenge`'
| @public
def onChallenge(self, challenge):
| raise Exception('received authentication challenge, but onChallenge not implemented')
|
'Errback any still outstanding requests with exc.'
| def _errback_outstanding_requests(self, exc):
| d = txaio.create_future_success(None)
all_requests = [self._publish_reqs, self._subscribe_reqs, self._unsubscribe_reqs, self._call_reqs, self._register_reqs, self._unregister_reqs]
outstanding = []
for requests in all_requests:
outstanding.extend(requests.values())
requests.clear()
i... |
'Implements :func:`autobahn.wamp.interfaces.ISession.onLeave`'
| @public
def onLeave(self, details):
| if (details.reason != CloseDetails.REASON_DEFAULT):
self.log.warn('session closed with reason {reason} [{message}]', reason=details.reason, message=details.message)
exc = ApplicationError(details.reason, details.message)
d = self._errback_outstanding_requests(exc)
def disconnect(_... |
'Implements :func:`autobahn.wamp.interfaces.ISession.leave`'
| @public
def leave(self, reason=None, message=None):
| if (not self._session_id):
raise SessionNotReady(u"session hasn't joined a realm")
if (not self._goodbye_sent):
if (not reason):
reason = u'wamp.close.normal'
msg = wamp.message.Goodbye(reason=reason, message=message)
self._transport.send(msg)
self... |
'Implements :func:`autobahn.wamp.interfaces.ISession.onDisconnect`'
| @public
def onDisconnect(self):
| exc = exception.TransportLost()
self._errback_outstanding_requests(exc)
|
'Implements :func:`autobahn.wamp.interfaces.IPublisher.publish`'
| @public
def publish(self, topic, *args, **kwargs):
| assert (type(topic) == six.text_type)
if (not self._transport):
raise exception.TransportLost()
options = kwargs.pop('options', None)
if (options and (not isinstance(options, types.PublishOptions))):
raise Exception('options must be of type a.w.t.PublishOptions')
reque... |
'Implements :func:`autobahn.wamp.interfaces.ISubscriber.subscribe`'
| @public
def subscribe(self, handler, topic=None, options=None):
| assert ((callable(handler) and (topic is not None)) or hasattr(handler, '__class__'))
assert ((topic is None) or (type(topic) == six.text_type))
assert ((options is None) or isinstance(options, types.SubscribeOptions))
if (not self._transport):
raise exception.TransportLost()
def _subscribe(... |
'Called from :meth:`autobahn.wamp.protocol.Subscription.unsubscribe`'
| def _unsubscribe(self, subscription):
| assert isinstance(subscription, Subscription)
assert subscription.active
assert (subscription.id in self._subscriptions)
assert (subscription in self._subscriptions[subscription.id])
if (not self._transport):
raise exception.TransportLost()
self._subscriptions[subscription.id].remove(sub... |
'Implements :func:`autobahn.wamp.interfaces.ICaller.call`'
| @public
def call(self, procedure, *args, **kwargs):
| assert (type(procedure) == six.text_type)
if (not self._transport):
raise exception.TransportLost()
options = kwargs.pop('options', None)
if (options and (not isinstance(options, types.CallOptions))):
raise Exception('options must be of type a.w.t.CallOptions')
request... |
'Implements :func:`autobahn.wamp.interfaces.ICallee.register`'
| @public
def register(self, endpoint, procedure=None, options=None):
| assert ((callable(endpoint) and (procedure is not None)) or hasattr(endpoint, '__class__'))
assert ((procedure is None) or (type(procedure) == six.text_type))
assert ((options is None) or isinstance(options, types.RegisterOptions))
if (not self._transport):
raise exception.TransportLost()
de... |
'Called from :meth:`autobahn.wamp.protocol.Registration.unregister`'
| def _unregister(self, registration):
| assert isinstance(registration, Registration)
assert registration.active
assert (registration.id in self._registrations)
if (not self._transport):
raise exception.TransportLost()
request_id = self._request_id_gen.next()
on_reply = txaio.create_future()
self._unregister_reqs[request_i... |
':param config: The default component configuration.
:type config: instance of :class:`autobahn.wamp.types.ComponentConfig`'
| def __init__(self, config=None):
| self.config = (config or types.ComponentConfig(realm=u'default'))
|
'Creates a new WAMP application session.
:returns: -- An instance of the WAMP application session class as
given by `self.session`.'
| def __call__(self):
| session = self.session(self.config)
session.factory = self
return session
|
'Unicode arguments in ApplicationError will not raise an exception when
str()\'d.'
| def test_unicode_str(self):
| error = ApplicationError(u'some.url', u'\u2603')
if PY3:
self.assertIn(u'\u2603', str(error))
else:
self.assertIn('\\u2603', str(error))
|
'Unicode arguments in ApplicationError will not raise an exception when
the error_message method is called.'
| def test_unicode_errormessage(self):
| error = ApplicationError(u'some.url', u'\u2603')
print error.error_message()
self.assertIn(u'\u2603', error.error_message())
|
'Test deep object equality assert (because I am paranoid).'
| def test_deep_equal(self):
| v = os.urandom(10)
o1 = [1, 2, {u'foo': u'bar', u'bar': v, u'baz': [9, 3, 2], u'goo': {u'moo': [1, 2, 3]}}, v]
o2 = [1, 2, {u'goo': {u'moo': [1, 2, 3]}, u'bar': v, u'baz': [9, 3, 2], u'foo': u'bar'}, v]
self.assertEqual(o1, o2)
|
'Test round-tripping over each serializer.'
| def test_roundtrip(self):
| for ser in self._test_serializers:
for (contains_binary, msg) in self._test_messages:
if (not must_skip(ser, contains_binary)):
(payload, binary) = ser.serialize(msg)
msg2 = ser.unserialize(payload, binary)
self.assertEqual([msg], msg2)
|
'Test cross-tripping over 2 serializers (as is done by WAMP routers).'
| def test_crosstrip(self):
| for ser1 in self._test_serializers:
for (contains_binary, msg) in self._test_messages:
if (not must_skip(ser1, contains_binary)):
(payload, binary) = ser1.serialize(msg)
msg1 = ser1.unserialize(payload, binary)
msg1 = msg1[0]
for se... |
'Test message serialization caching.'
| def test_caching(self):
| for (contains_binary, msg) in self._test_messages:
self.assertEqual(msg._serialized, {})
for ser in self._test_serializers:
if (not must_skip(ser, contains_binary)):
self.assertFalse((ser._serializer in msg._serialized))
(payload, binary) = ser.serialize(m... |
'Retain, when not specified, is False-y by default.'
| def test_retain_default_false(self):
| wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1']
msg = message.Publish.parse(wmsg)
self.assertIsInstance(msg, message.Publish)
self.assertEqual(msg.retain, None)
self.assertIsNot(msg.retain, True)
self.ass... |
'Retain, when specified as False, shows up in the message.'
| def test_retain_explicit_false(self):
| wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1']
msg = message.Publish.parse(wmsg)
self.assertIsInstance(msg, message.Publish)
self.assertEqual(msg.retain, False)
self.assertIsNot(msg.retain,... |
'Retain, when specified as True, shows up in the message.'
| def test_retain_explicit_true(self):
| wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': True, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1']
msg = message.Publish.parse(wmsg)
self.assertIsInstance(msg, message.Publish)
self.assertEqual(msg.retain, True)
self.assertIs(msg.retain, True... |
'Compare this message to another message for equality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are equal.
:rtype: bool'
| def __eq__(self, other):
| if (not isinstance(other, self.__class__)):
return False
for k in self.__slots__:
if (k not in ['_serialized']):
if (not (getattr(self, k) == getattr(other, k))):
return False
return True
|
'Compare this message to another message for inequality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are not equal.
:rtype: bool'
| def __ne__(self, other):
| return (not self.__eq__(other))
|
'Resets the serialization cache.'
| def uncache(self):
| self._serialized = {}
|
'Serialize this object into a wire level bytes representation and cache
the resulting bytes. If the cache already contains an entry for the given
serializer, return the cached representation directly.
:param serializer: The wire level serializer to use.
:type serializer: An instance that implements :class:`autobahn.int... | def serialize(self, serializer):
| if (serializer not in self._serialized):
self._serialized[serializer] = serializer.serialize(self.marshal())
return self._serialized[serializer]
|
':param realm: The URI of the WAMP realm to join.
:type realm: str
:param roles: The WAMP session roles and features to announce.
:type roles: dict of :class:`autobahn.wamp.role.RoleFeatures`
:param authmethods: The authentication methods to announce.
:type authmethods: list of str or None
:param authid: The authentica... | def __init__(self, realm, roles, authmethods=None, authid=None, authrole=None, authextra=None, resumable=None, resume_session=None, resume_token=None):
| assert ((realm is None) or isinstance(realm, six.text_type))
assert (type(roles) == dict)
assert (len(roles) > 0)
for role in roles:
assert (role in [u'subscriber', u'publisher', u'caller', u'callee'])
assert isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role])
if aut... |
'Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.'
| @staticmethod
def parse(wmsg):
| assert ((len(wmsg) > 0) and (wmsg[0] == Hello.MESSAGE_TYPE))
if (len(wmsg) != 3):
raise ProtocolError('invalid message length {0} for HELLO'.format(len(wmsg)))
realm = check_or_raise_uri(wmsg[1], u"'realm' in HELLO", allow_none=True)
details = check_or_raise_extra(wmsg[2], u... |
'Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list'
| def marshal(self):
| details = {u'roles': {}}
for role in self.roles.values():
details[u'roles'][role.ROLE] = {}
for feature in role.__dict__:
if ((not feature.startswith('_')) and (feature != 'ROLE') and (getattr(role, feature) is not None)):
if (u'features' not in details[u'roles'][role... |
'Return a string representation of this message.'
| def __str__(self):
| return u'Hello(realm={}, roles={}, authmethods={}, authid={}, authrole={}, authextra={}, resumable={}, resume_session={}, resume_token={})'.format(self.realm, self.roles, self.authmethods, self.authid, self.authrole, self.authextra, self.resumable, self.resume_session, self.resume_token)
|
':param session: The WAMP session ID the other peer is assigned.
:type session: int
:param roles: The WAMP roles to announce.
:type roles: dict of :class:`autobahn.wamp.role.RoleFeatures`
:param realm: The effective realm the session is joined on.
:type realm: str or None
:param authid: The authentication ID assigned.
... | def __init__(self, session, roles, realm=None, authid=None, authrole=None, authmethod=None, authprovider=None, authextra=None, resumed=None, resumable=None, resume_token=None, custom=None):
| assert (type(session) in six.integer_types)
assert (type(roles) == dict)
assert (len(roles) > 0)
for role in roles:
assert (role in [u'broker', u'dealer'])
assert isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role])
assert ((realm is None) or (type(realm) == six.text_... |
'Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.'
| @staticmethod
def parse(wmsg):
| assert ((len(wmsg) > 0) and (wmsg[0] == Welcome.MESSAGE_TYPE))
if (len(wmsg) != 3):
raise ProtocolError('invalid message length {0} for WELCOME'.format(len(wmsg)))
session = check_or_raise_id(wmsg[1], u"'session' in WELCOME")
details = check_or_raise_extra(wmsg[2], u"'detail... |
'Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list'
| def marshal(self):
| details = {}
details.update(self.custom)
if self.realm:
details[u'realm'] = self.realm
if self.authid:
details[u'authid'] = self.authid
if self.authrole:
details[u'authrole'] = self.authrole
if self.authrole:
details[u'authmethod'] = self.authmethod
if self.au... |
'Returns string representation of this message.'
| def __str__(self):
| return u'Welcome(session={}, roles={}, realm={}, authid={}, authrole={}, authmethod={}, authprovider={}, authextra={}, resumed={}, resumable={}, resume_token={})'.format(self.session, self.roles, self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra... |
':param reason: WAMP or application error URI for aborting reason.
:type reason: str
:param message: Optional human-readable closing message, e.g. for logging purposes.
:type message: str or None'
| def __init__(self, reason, message=None):
| assert (type(reason) == six.text_type)
assert ((message is None) or (type(message) == six.text_type))
Message.__init__(self)
self.reason = reason
self.message = message
|
'Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.'
| @staticmethod
def parse(wmsg):
| assert ((len(wmsg) > 0) and (wmsg[0] == Abort.MESSAGE_TYPE))
if (len(wmsg) != 3):
raise ProtocolError('invalid message length {0} for ABORT'.format(len(wmsg)))
details = check_or_raise_extra(wmsg[1], u"'details' in ABORT")
reason = check_or_raise_uri(wmsg[2], u"'reason' i... |
'Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list'
| def marshal(self):
| details = {}
if self.message:
details[u'message'] = self.message
return [Abort.MESSAGE_TYPE, details, self.reason]
|
'Returns string representation of this message.'
| def __str__(self):
| return u'Abort(message={0}, reason={1})'.format(self.message, self.reason)
|
':param method: The authentication method.
:type method: str
:param extra: Authentication method specific information.
:type extra: dict or None'
| def __init__(self, method, extra=None):
| assert (type(method) == six.text_type)
assert ((extra is None) or (type(extra) == dict))
Message.__init__(self)
self.method = method
self.extra = (extra or {})
|
'Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.'
| @staticmethod
def parse(wmsg):
| assert ((len(wmsg) > 0) and (wmsg[0] == Challenge.MESSAGE_TYPE))
if (len(wmsg) != 3):
raise ProtocolError('invalid message length {0} for CHALLENGE'.format(len(wmsg)))
method = wmsg[1]
if (type(method) != six.text_type):
raise ProtocolError("invalid type {0} for ... |
'Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list'
| def marshal(self):
| return [Challenge.MESSAGE_TYPE, self.method, self.extra]
|
'Returns string representation of this message.'
| def __str__(self):
| return u'Challenge(method={0}, extra={1})'.format(self.method, self.extra)
|
':param signature: The signature for the authentication challenge.
:type signature: str
:param extra: Authentication method specific information.
:type extra: dict or None'
| def __init__(self, signature, extra=None):
| assert (type(signature) == six.text_type)
assert ((extra is None) or (type(extra) == dict))
Message.__init__(self)
self.signature = signature
self.extra = (extra or {})
|
'Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.'
| @staticmethod
def parse(wmsg):
| assert ((len(wmsg) > 0) and (wmsg[0] == Authenticate.MESSAGE_TYPE))
if (len(wmsg) != 3):
raise ProtocolError('invalid message length {0} for AUTHENTICATE'.format(len(wmsg)))
signature = wmsg[1]
if (type(signature) != six.text_type):
raise ProtocolError("invalid type ... |
'Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list'
| def marshal(self):
| return [Authenticate.MESSAGE_TYPE, self.signature, self.extra]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.