本文整理汇总了Python中pytrie.StringTrie.longest_prefix_value方法的典型用法代码示例。如果您正苦于以下问题:Python StringTrie.longest_prefix_value方法的具体用法?Python StringTrie.longest_prefix_value怎么用?Python StringTrie.longest_prefix_value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytrie.StringTrie
的用法示例。
在下文中一共展示了StringTrie.longest_prefix_value方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_empty_tree
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
def test_empty_tree(self):
"""
Test trie ctor, and that is doesn't match on "any" prefix.
"""
t = StringTrie()
for key in [u'', u'f', u'foo', u'foobar']:
with self.assertRaises(KeyError):
t.longest_prefix_value(key)
示例2: test_longest_prefix_3
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
def test_longest_prefix_3(self):
"""
Test non-matching prefix lookups.
"""
t = StringTrie()
for key in [u'x', u'fop', u'foobar']:
t[key] = key
for key in [u'y', u'yfoo', u'fox', u'fooba']:
with self.assertRaises(KeyError):
t.longest_prefix_value(key)
示例3: __init__
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class FIB:
def __init__(self):
self.fib = StringTrie()
self.fib["/mbandeira"] = "int1"
self.fib["/cdrummond"] = "int2"
def getIface(self, contentName):
return self.fib.longest_prefix_value(contentName)
示例4: test_longest_prefix_1
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
def test_longest_prefix_1(self):
"""
Test that keys are detected as prefix of themselfes.
"""
t = StringTrie()
test_keys = [u'f', u'foo', u'foobar', u'baz']
for key in test_keys:
t[key] = key
for key in test_keys:
self.assertEqual(t.longest_prefix_value(key), key)
示例5: test_longest_prefix_4
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
def test_longest_prefix_4(self):
"""
Test that a trie with an empty string as a key contained
matches a non-empty prefix matching lookup.
"""
self.skip = True
# stored_key = u'x' # this works (and of course it should!)
stored_key = u'' # this blows up! (and it _should_ work)
test_key = u'xyz'
t = StringTrie()
t[stored_key] = stored_key
self.assertTrue(stored_key in t)
self.assertTrue(test_key.startswith(stored_key))
self.assertEqual(t.longest_prefix_value(test_key), stored_key)
示例6: test_longest_prefix_2
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
def test_longest_prefix_2(self):
"""
Test matching prefix lookups.
"""
t = StringTrie()
test_keys = [u'f', u'foo', u'foobar']
for key in test_keys:
t[key] = key
test_keys = {
u'foobarbaz': u'foobar',
u'foobaz': u'foo',
u'fool': u'foo',
u'foo': u'foo',
u'fob': u'f',
u'fo': u'f',
u'fx': u'f',
u'f': u'f',
}
for key in test_keys:
self.assertEqual(t.longest_prefix_value(key), test_keys[key])
示例7: UriObservationMap
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
#.........这里部分代码省略.........
observations.append(observation)
uri_parts = tuple(uri.split('.'))
uri_parts_len = len(uri_parts)
if uri_parts_len in self._observations_wildcard_patterns:
for pattern in self._observations_wildcard_patterns[uri_parts_len]:
patterned_uri = '.'.join(['' if pattern[i] else uri_parts[i] for i in range(uri_parts_len)])
if patterned_uri in self._observations_wildcard:
observations.append(self._observations_wildcard[patterned_uri])
return observations
def best_matching_observation(self, uri):
"""
Returns the observation that best matches the given URI. This is the core method called
by a dealer to actually forward calls.
:param uri: The URI to match.
:type uri: unicode
:returns: The observation best matching the URI. This is an instance of
``ExactUriObservation``, ``PrefixUriObservation`` or ``WildcardUriObservation`` or ``None``.
:rtype: obj or None
"""
# a exact matching observation is always "best", if any
#
if uri in self._observations_exact:
return self._observations_exact[uri]
# "second best" is the longest prefix-matching observation, if any
# FIXME: do we want this to take precedence over _any_ wildcard (see below)?
#
try:
return self._observations_prefix.longest_prefix_value(uri)
except KeyError:
pass
# FIXME: for wildcard observations, when there are multiple matching, we'd
# like to deterministically select the "most selective one"
# We first need a definition of "most selective", and then we need to implement
# this here.
#
uri_parts = tuple(uri.split('.'))
uri_parts_len = len(uri_parts)
if uri_parts_len in self._observations_wildcard_patterns:
for pattern in self._observations_wildcard_patterns[uri_parts_len]:
patterned_uri = '.'.join(['' if pattern[i] else uri_parts[i] for i in range(uri_parts_len)])
if patterned_uri in self._observations_wildcard:
return self._observations_wildcard[patterned_uri]
def get_observation_by_id(self, id):
"""
Get a observation by ID.
:param id: The ID of the observation to retrieve.
:type id: int
:returns: The observation for the given ID or ``None``.
:rtype: obj or None
"""
return self._observation_id_to_observation.get(id, None)
def drop_observer(self, observer, observation):
"""
Drop a observer from a observation.
示例8: RouterRoleStaticAuth
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class RouterRoleStaticAuth(RouterRole):
"""
A role on a router realm that is authorized using a static configuration.
"""
def __init__(self, router, uri, permissions=None, default_permissions=None, debug=False):
"""
Ctor.
:param uri: The URI of the role.
:type uri: str
:param permissions: A permissions configuration, e.g. a list
of permission dicts like `{'uri': 'com.example.*', 'call': True}`
:type permissions: list
:param debug: Enable debug logging.
:type debug: bool
"""
RouterRole.__init__(self, router, uri, debug)
self.permissions = permissions or []
self._urimap = StringTrie()
self._default = default_permissions or RouterPermissions('', True, False, False, False, False)
for p in self.permissions:
uri = p['uri']
if len(uri) > 0 and uri[-1] == '*':
match_by_prefix = True
uri = uri[:-1]
else:
match_by_prefix = False
perms = RouterPermissions(uri, match_by_prefix,
call=p.get('call', False),
register=p.get('register', False),
publish=p.get('publish', False),
subscribe=p.get('subscribe', False))
if len(uri) > 0:
self._urimap[uri] = perms
else:
self._default = perms
def authorize(self, session, uri, action):
"""
Authorize a session connected under this role to perform the given action
on the given URI.
:param session: The WAMP session that requests the action.
:type session: Instance of :class:`autobahn.wamp.protocol.ApplicationSession`
:param uri: The URI on which to perform the action.
:type uri: str
:param action: The action to be performed.
:type action: str
:return: bool -- Flag indicating whether session is authorized or not.
"""
if self.debug:
log.msg("CrossbarRouterRoleStaticAuth.authorize", self.uri, uri, action)
# if action == 'publish':
# f = 1/0
try:
permissions = self._urimap.longest_prefix_value(uri)
if not permissions.match_by_prefix and uri != permissions.uri:
return False
return getattr(permissions, action)
except KeyError:
return getattr(self._default, action)
示例9: RouterRoleStaticAuth
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class RouterRoleStaticAuth(RouterRole):
"""
A role on a router realm that is authorized using a static configuration.
"""
def __init__(self, router, uri, permissions=None, default_permissions=None):
"""
:param router: The router this role is defined on.
:type router: obj
:param uri: The URI of the role.
:type uri: unicode
:param permissions: A permissions configuration, e.g. a list
of permission dicts like `{'uri': 'com.example.*', 'call': True}`
:type permissions: list of dict
:param default_permissions: The default permissions to apply when no other
configured permission matches. The default permissions when not explicitly
set is to deny all actions on all URIs!
:type default_permissions: dict
"""
RouterRole.__init__(self, router, uri)
assert(permissions is None or type(permissions) == list)
if permissions:
for p in permissions:
assert(type(p) == dict)
assert(default_permissions is None or type(default_permissions) == dict)
# default permissions (used when nothing else is matching)
# note: default permissions have their matching URI and match policy set to None!
if default_permissions:
self._default = RouterPermissions.from_dict(default_permissions)
else:
self._default = RouterPermissions(None, None,
call=False,
register=False,
publish=False,
subscribe=False,
disclose_caller=False,
disclose_publisher=False,
cache=True)
# Trie of explicitly configured permissions
self._permissions = StringTrie()
for obj in permissions or []:
perms = RouterPermissions.from_dict(obj)
self._permissions[perms.uri] = perms
def authorize(self, session, uri, action):
"""
Authorize a session connected under this role to perform the given
action on the given URI.
:param session: The WAMP session that requests the action.
:type session: Instance of :class:`autobahn.wamp.protocol.ApplicationSession`
:param uri: The URI on which to perform the action.
:type uri: str
:param action: The action to be performed.
:type action: str
:return: bool -- Flag indicating whether session is authorized or not.
"""
self.log.debug(
"CrossbarRouterRoleStaticAuth.authorize {myuri} {uri} {action}",
myuri=self.uri, uri=uri, action=action)
try:
# longest prefix match of the URI to be authorized against our Trie
# of configured URIs for permissions
permissions = self._permissions.longest_prefix_value(uri)
# if there is a _prefix_ matching URI, check that this is actually the
# match policy on the permission (otherwise, apply default permissions)!
if permissions.match != u'prefix' and uri != permissions.uri:
permissions = self._default
except KeyError:
# workaround because of https://bitbucket.org/gsakkis/pytrie/issues/4/string-keys-of-zero-length-are-not
if u'' in self._permissions:
permissions = self._permissions[u'']
else:
permissions = self._default
if action == u'publish':
return {
u'allow': permissions.publish,
u'disclose': permissions.disclose_publisher,
u'cache': permissions.cache
}
elif action == u'subscribe':
return {
u'allow': permissions.subscribe,
u'cache': permissions.cache
}
elif action == u'call':
return {
u'allow': permissions.call,
u'disclose': permissions.disclose_caller,
#.........这里部分代码省略.........
示例10: UriObservationMap
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
#.........这里部分代码省略.........
for observation in self._observations_prefix.iter_prefix_values(uri):
observations.append(observation)
for observation in self._observations_wildcard.iter_matches(uri):
observations.append(observation)
return observations
def best_matching_observation(self, uri):
"""
Returns the observation that best matches the given URI. This is the core method called
by a dealer to actually forward calls.
:param uri: The URI to match.
:type uri: unicode
:returns: The observation best matching the URI. This is an instance of
``ExactUriObservation``, ``PrefixUriObservation`` or ``WildcardUriObservation`` or ``None``.
:rtype: obj or None
"""
if not isinstance(uri, six.text_type):
raise Exception("'uri' should be unicode, not {}".format(type(uri).__name__))
# a exact matching observation is always "best", if any
#
if uri in self._observations_exact:
return self._observations_exact[uri]
# "second best" is the longest prefix-matching observation, if any
# FIXME: do we want this to take precedence over _any_ wildcard (see below)?
#
try:
return self._observations_prefix.longest_prefix_value(uri)
except KeyError:
pass
# FIXME: for wildcard observations, when there are multiple matching, we'd
# like to deterministically select the "most selective one"
# We first need a definition of "most selective", and then we need to implement
# this here.
#
for observation in self._observations_wildcard.iter_matches(uri):
return observation
def get_observation_by_id(self, id):
"""
Get a observation by ID.
:param id: The ID of the observation to retrieve.
:type id: int
:returns: The observation for the given ID or ``None``.
:rtype: obj or None
"""
return self._observation_id_to_observation.get(id, None)
def drop_observer(self, observer, observation):
"""
Drop a observer from a observation.
:param observer: The observer to drop from the given observation.
:type observer: obj
:param observation: The observation from which to drop the observer. An instance
of ``ExactUriObservation``, ``PrefixUriObservation`` or ``WildcardUriObservation`` previously
created and handed out by this observation map.
示例11: KeyRing
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class KeyRing(object):
"""
A keyring holds (cryptobox) public-private key pairs for use with WAMP-cryptobox payload
encryption. The keyring can be set on a WAMP session and then transparently will get used
for encrypting and decrypting WAMP message payloads.
"""
@public
def __init__(self, default_key=None):
"""
Create a new key ring to hold public and private keys mapped from an URI space.
"""
assert(default_key is None or isinstance(default_key, Key) or type(default_key == six.text_type))
self._uri_to_key = StringTrie()
if type(default_key) == six.text_type:
default_key = Key(originator_priv=default_key, responder_priv=default_key)
self._default_key = default_key
@public
def generate_key(self):
"""
Generate a new private key and return a pair with the base64 encodings
of (priv_key, pub_key).
"""
key = PrivateKey.generate()
priv_key = key.encode(encoder=Base64Encoder)
pub_key = key.public_key.encode(encoder=Base64Encoder)
return (u'{}'.format(priv_key), u'{}'.format(pub_key))
@public
def set_key(self, uri, key):
"""
Add a key set for a given URI.
"""
assert(type(uri) == six.text_type)
assert(key is None or isinstance(key, Key) or type(key) == six.text_type)
if type(key) == six.text_type:
key = Key(originator_priv=key, responder_priv=key)
if uri == u'':
self._default_key = key
else:
if key is None:
if uri in self._uri_to_key:
del self._uri_to_key[uri]
else:
self._uri_to_key[uri] = key
@public
def rotate_key(self, uri):
assert(type(uri) == six.text_type)
if uri in self._uri_to_key:
self._uri_to_key[uri].rotate()
else:
self._uri_to_key[uri].rotate()
def _get_box(self, is_originating, uri, match_exact=False):
try:
if match_exact:
key = self._uri_to_key[uri]
else:
key = self._uri_to_key.longest_prefix_value(uri)
except KeyError:
if self._default_key:
key = self._default_key
else:
return None
if is_originating:
return key.originator_box
else:
return key.responder_box
@public
def encode(self, is_originating, uri, args=None, kwargs=None):
"""
Encrypt the given WAMP URI, args and kwargs into an EncodedPayload instance, or None
if the URI should not be encrypted.
"""
assert(type(is_originating) == bool)
assert(type(uri) == six.text_type)
assert(args is None or type(args) in (list, tuple))
assert(kwargs is None or type(kwargs) == dict)
box = self._get_box(is_originating, uri)
if not box:
# if we didn't find a crypto box, then return None, which
# signals that the payload travel unencrypted (normal)
return None
payload = {
u'uri': uri,
u'args': args,
u'kwargs': kwargs
}
nonce = random(Box.NONCE_SIZE)
payload_ser = _json_dumps(payload).encode('utf8')
payload_encr = box.encrypt(payload_ser, nonce, encoder=RawEncoder)
#.........这里部分代码省略.........
示例12: WampMQTTServerFactory
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class WampMQTTServerFactory(Factory):
log = make_logger()
protocol = WampMQTTServerProtocol
serializers = {
u'json': JsonObjectSerializer(),
u'msgpack': MsgPackObjectSerializer(),
u'cbor': CBORObjectSerializer(),
u'ubjson': UBJSONObjectSerializer(),
}
def __init__(self, router_session_factory, config, reactor):
self._router_session_factory = router_session_factory
self._router_factory = router_session_factory._routerFactory
self._options = config.get(u'options', {})
self._realm = self._options.get(u'realm', None)
self._reactor = reactor
self._payload_mapping = StringTrie()
for topic, pmap in self._options.get(u'payload_mapping', {}).items():
self._set_payload_format(topic, pmap)
def buildProtocol(self, addr):
protocol = self.protocol(self._reactor)
protocol.factory = self
return protocol
def _get_payload_format(self, topic):
"""
Map a WAMP topic URI to MQTT payload format.
:param topic: WAMP URI.
:type topic: str
:returns: Payload format metadata.
:rtype: dict
"""
try:
pmap = self._payload_mapping.longest_prefix_value(topic)
except KeyError:
return None
else:
return pmap
def _set_payload_format(self, topic, pmap=None):
if pmap is None:
if topic in self._payload_mapping:
del self._payload_mapping[topic]
else:
self._payload_mapping[topic] = pmap
@inlineCallbacks
def transform_wamp(self, topic, msg):
# check for cached transformed payload
cache_key = u'_{}_{}'.format(self.__class__.__name__, id(self))
cached = msg._serialized.get(cache_key, None)
if cached:
payload_format, mapped_topic, payload = cached
self.log.debug('using cached payload for {cache_key} in message {msg_id}!', msg_id=id(msg), cache_key=cache_key)
else:
# convert WAMP URI to MQTT topic
mapped_topic = _wamp_topic_to_mqtt(topic)
# for WAMP->MQTT, the payload mapping is determined from the
# WAMP URI (not the transformed MQTT topic)
payload_format = self._get_payload_format(topic)
payload_format_type = payload_format[u'type']
if payload_format_type == u'passthrough':
payload = msg.payload
elif payload_format_type == u'native':
serializer = payload_format.get(u'serializer', None)
payload = self._transform_wamp_native(serializer, msg)
elif payload_format_type == u'dynamic':
encoder = payload_format.get(u'encoder', None)
codec_realm = payload_format.get(u'realm', self._realm)
payload = yield self._transform_wamp_dynamic(encoder, codec_realm, mapped_topic, topic, msg)
else:
raise Exception('payload format {} not implemented'.format(payload_format))
msg._serialized[cache_key] = (payload_format, mapped_topic, payload)
self.log.debug('transform_wamp({topic}, {msg}) -> payload_format={payload_format}, mapped_topic={mapped_topic}, payload={payload}', topic=topic, msg=msg, payload_format=payload_format, mapped_topic=mapped_topic, payload=payload)
returnValue((payload_format, mapped_topic, payload))
@inlineCallbacks
def _transform_wamp_dynamic(self, encoder, codec_realm, mapped_topic, topic, msg):
codec_session = self._router_factory.get(codec_realm)._realm.session
payload = yield codec_session.call(encoder, mapped_topic, topic, msg.args, msg.kwargs)
returnValue(payload)
def _transform_wamp_native(self, serializer, msg):
obj = {}
for opt in [u'args',
u'kwargs',
u'exclude',
u'exclude_authid',
#.........这里部分代码省略.........
示例13: RouterRoleStaticAuth
# 需要导入模块: from pytrie import StringTrie [as 别名]
# 或者: from pytrie.StringTrie import longest_prefix_value [as 别名]
class RouterRoleStaticAuth(RouterRole):
"""
A role on a router realm that is authorized using a static configuration.
"""
def __init__(self, router, uri, permissions=None, default_permissions=None):
"""
:param router: The router this role is defined on.
:type router: obj
:param uri: The URI of the role.
:type uri: unicode
:param permissions: A permissions configuration, e.g. a list
of permission dicts like `{'uri': 'com.example.*', 'call': True}`
:type permissions: list of dict
:param default_permissions: The default permissions to apply when no other
configured permission matches. The default permissions when not explicitly
set is to deny all actions on all URIs!
:type default_permissions: dict
"""
RouterRole.__init__(self, router, uri)
assert(permissions is None or isinstance(permissions, list))
if permissions:
for p in permissions:
assert(isinstance(p, dict))
assert(default_permissions is None or isinstance(default_permissions, dict))
# default permissions (used when nothing else is matching)
# note: default permissions have their matching URI and match policy set to None!
if default_permissions:
self._default = RouterPermissions.from_dict(default_permissions)
else:
self._default = RouterPermissions(None, None,
call=False,
register=False,
publish=False,
subscribe=False,
disclose_caller=False,
disclose_publisher=False,
cache=True)
# Trie of explicitly configured permissions
self._permissions = StringTrie()
self._wild_permissions = StringTrie()
# for "wildcard" URIs, there will be a ".." in them somewhere,
# and so we want to match on the biggest prefix
# (i.e. everything to the left of the first "..")
for obj in permissions or []:
perms = RouterPermissions.from_dict(obj)
if '..' in perms.uri:
trunc = perms.uri[:perms.uri.index('..')]
self._wild_permissions[trunc] = perms
else:
self._permissions[perms.uri] = perms
def authorize(self, session, uri, action, options):
"""
Authorize a session connected under this role to perform the given
action on the given URI.
:param session: The WAMP session that requests the action.
:type session: Instance of :class:`autobahn.wamp.protocol.ApplicationSession`
:param uri: The URI on which to perform the action.
:type uri: str
:param action: The action to be performed.
:type action: str
:return: bool -- Flag indicating whether session is authorized or not.
"""
self.log.debug(
"CrossbarRouterRoleStaticAuth.authorize {myuri} {uri} {action}",
myuri=self.uri, uri=uri, action=action)
try:
# longest prefix match of the URI to be authorized against our Trie
# of configured URIs for permissions
permissions = self._permissions.longest_prefix_value(uri)
# if there is a _prefix_ matching URI, check that this is actually the
# match policy on the permission (otherwise, apply default permissions)!
if permissions.match != u'prefix' and uri != permissions.uri:
permissions = self._default
except KeyError:
# workaround because of https://bitbucket.org/gsakkis/pytrie/issues/4/string-keys-of-zero-length-are-not
permissions = self._permissions.get(u'', self._default)
# if we found a non-"exact" match, there might be a better one in the wildcards
if permissions.match != u'exact':
try:
wildperm = self._wild_permissions.longest_prefix_value(uri)
Pattern(wildperm.uri, Pattern.URI_TARGET_ENDPOINT).match(uri)
except (KeyError, Exception):
# match() raises Exception on no match
wildperm = None
if wildperm is not None:
permissions = wildperm
#.........这里部分代码省略.........