当前位置: 首页>>代码示例>>Python>>正文


Python Name.match方法代码示例

本文整理汇总了Python中pyndn.name.Name.match方法的典型用法代码示例。如果您正苦于以下问题:Python Name.match方法的具体用法?Python Name.match怎么用?Python Name.match使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyndn.name.Name的用法示例。


在下文中一共展示了Name.match方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: InterestFilter

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import match [as 别名]
class InterestFilter(object):
    """
    Create an InterestFilter to match any Interest whose name starts with the
    given prefix. If the optional regexFilter is provided then the remaining
    components match the regexFilter regular expression as described in
    doesMatch.

    :param prefix: The prefix. If a Name then this makes a copy of the Name.
      Otherwise it create a Name from the URI string.
    :type prefix: Name or str
    :param str regexFilter: (optional) The regular expression for matching the
      remaining name components.
    """
    def __init__(self, prefix, regexFilter = None):
        if type(prefix) is InterestFilter:
            interestFilter = prefix
            # The copy constructor.
            self._prefix = Name(interestFilter._prefix)
            self._regexFilter = interestFilter._regexFilter
            self._regexFilterPattern = interestFilter._regexFilterPattern
        else:
            self._prefix = Name(prefix)
            self._regexFilter = regexFilter
            if regexFilter != None:
                self._regexFilterPattern = self.makePattern(regexFilter)
            else:
                self._regexFilterPattern = None

    def doesMatch(self, name):
        """
        Check if the given name matches this filter. Match if name starts with
        this filter's prefix. If this filter has the optional regexFilter then
        the remaining components match the regexFilter regular expression.
        For example, the following InterestFilter:

           InterestFilter("/hello", "<world><>+")

        will match all Interests, whose name has the prefix `/hello` which is
        followed by a component `world` and has at least one more component
        after it. Examples:

           /hello/world/!
           /hello/world/x/y/z

        Note that the regular expression will need to match all remaining
        components (e.g., there are implicit heading `^` and trailing `$`
        symbols in the regular expression).

        :param Name name: The name to check against this filter.
        :return: True if name matches this filter, otherwise False.
        :rtype: bool
        """
        if len(name) < len(self._prefix):
            return False

        if self.hasRegexFilter():
            # Perform a prefix match and regular expression match for the
            # remaining components.
            if not self._prefix.match(name):
                return False

            return None != NdnRegexMatcher.match(
              self._regexFilterPattern, name.getSubName(len(self._prefix)))
        else:
            # Just perform a prefix match.
            return self._prefix.match(name)

    def getPrefix(self):
        """
        Get the prefix given to the constructor.

        :return: The prefix Name which you should not modify.
        :rtype: Name
        """
        return self._prefix

    def hasRegexFilter(self):
        """
        Check if a regexFilter was supplied to the constructor.

        :return: True if a regexFilter was supplied to the constructor.
        :rtype: bool
        """
        return self._regexFilter != None

    def getRegexFilter(self):
        """
        Get the regex filter. This is only valid if hasRegexFilter() is True.

        :return: The regular expression for matching the remaining name
          components.
        :rtype: str
        """
        return self._regexFilter

    @staticmethod
    def makePattern(regexFilter):
        """
        If regexFilter doesn't already have them, add ^ to the beginning and $
        to the end since these are required by NdnRegexMatcher.match.
#.........这里部分代码省略.........
开发者ID:mjycom,项目名称:PyNDN2,代码行数:103,代码来源:interest_filter.py

示例2: Node

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import match [as 别名]
class Node(object):
    """
    Create a new Node for communication with an NDN hub with the given Transport
    object and connectionInfo.

    :param Transport transport: An object of a subclass of Transport used for
      communication.
    :param Transport.ConnectionInfo connectionInfo: An object of a subclass of
      Transport.ConnectionInfo to be used to connect to the transport.
    """
    def __init__(self, transport, connectionInfo):
        self._transport = transport
        self._connectionInfo = connectionInfo
        self._pendingInterestTable = PendingInterestTable()
        self._interestFilterTable = InterestFilterTable()
        self._registeredPrefixTable = RegisteredPrefixTable(self._interestFilterTable)
        self._delayedCallTable = DelayedCallTable()
        # An array of function objects
        self._onConnectedCallbacks = []
        self._commandInterestGenerator = CommandInterestGenerator()
        self._timeoutPrefix = Name("/local/timeout")
        self._lastEntryId = 0
        self._lastEntryIdLock = threading.Lock()
        self._connectStatus = Node._ConnectStatus.UNCONNECTED

    def expressInterest(
      self, pendingInterestId, interestCopy, onData, onTimeout, onNetworkNack,
      wireFormat, face):
        """
        Send the Interest through the transport, read the entire response and
        call onData, onTimeout or onNetworkNack as described below.

        :param int pendingInterestId: The getNextEntryId() for the pending
          interest ID which Face got so it could return it to the caller.
        :param Interest interestCopy: The Interest which is NOT copied for this
          internal Node method.  The Face expressInterest is responsible for
          making a copy for Node to use.
        :param onData: When a matching data packet is received, this calls
          onData(interest, data) where interest is the Interest given to
          expressInterest and data is the received Data object.
        :type onData: function object
        :param onTimeout: If the interest times out according to the interest
          lifetime, this calls onTimeout(interest) where interest is the
          Interest given to expressInterest. If onTimeout is None, this does not
          use it.
        :type onTimeout: function object
        :param onNetworkNack: When a network Nack packet for the interest is
          received and onNetworkNack is not None, this calls
          onNetworkNack(interest, networkNack) and does not call onTimeout.
          interest is the sent Interest and networkNack is the received
          NetworkNack. However, if a network Nack is received and onNetworkNack
          is None, do nothing and wait for the interest to time out.
        :type onNetworkNack: function object
        :param wireFormat: A WireFormat object used to encode the message.
        :type wireFormat: a subclass of WireFormat
        :param Face face: The face which has the callLater method, used for
          interest timeouts. The callLater method may be overridden in a
          subclass of Face.
        :throws: RuntimeError If the encoded interest size exceeds
          getMaxNdnPacketSize().
        """
        # Set the nonce in our copy of the Interest so it is saved in the PIT.
        interestCopy.setNonce(Node._nonceTemplate)
        interestCopy.refreshNonce()

        if self._connectStatus == self._ConnectStatus.CONNECT_COMPLETE:
            # We are connected. Simply send the interest.
            self._expressInterestHelper(
              pendingInterestId, interestCopy, onData, onTimeout, onNetworkNack,
              wireFormat, face)
            return

        # TODO: Properly check if we are already connected to the expected host.
        if not self._transport.isAsync():
            # The simple case: Just do a blocking connect and express.
            self._transport.connect(self._connectionInfo, self, None);
            self._expressInterestHelper(pendingInterestId,
              interestCopy, onData, onTimeout, onNetworkNack, wireFormat, face)
            # Make future calls to expressInterest send directly to the Transport.
            self._connectStatus = self._ConnectStatus.CONNECT_COMPLETE

            return

        # Handle the async case.
        if self._connectStatus == Node._ConnectStatus.UNCONNECTED:
            self._connectStatus = Node._ConnectStatus.CONNECT_REQUESTED

            # expressInterestHelper will be called by onConnected.
            self._onConnectedCallbacks.append(
              lambda: self._expressInterestHelper
                (pendingInterestId, interestCopy, onData, onTimeout,
                 onNetworkNack, wireFormat, face))

            def onConnected():
                # Assume that further calls to expressInterest dispatched to the
                # event loop are queued and won't enter expressInterest until
                # this method completes and sets CONNECT_COMPLETE.
                # Call each callback added while the connection was opening.
                for onConnectedCallback in self._onConnectedCallbacks:
                    onConnectedCallback()
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例3: Consumer

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import match [as 别名]
class Consumer(object):
    """
    Create a Consumer to use the given ConsumerDb, Face and other values.

    :param Face face: The face used for data packet and key fetching.
    :param KeyChain keyChain: The keyChain used to verify data packets.
    :param Name groupName: The reading group name that the consumer belongs to.
      This makes a copy of the Name.
    :param Name consumerName: The identity of the consumer. This makes a copy of
      the Name.
    :param ConsumerDb database: The ConsumerDb database for storing decryption
      keys.
    :param Link cKeyLink: (optional) The Link object to use in Interests for
      C-KEY retrieval. This makes a copy of the Link object. If the Link
      object's getDelegations().size() is zero, don't use it. If omitted, don't
      use a Link object.
    :param Link dKeyLink: (optional) The Link object to use in Interests for
      D-KEY retrieval. This makes a copy of the Link object. If the Link
      object's getDelegations().size() is zero, don't use it. If omitted, don't
      use a Link object.
    """
    def __init__(self, face, keyChain, groupName, consumerName, database,
          cKeyLink = None, dKeyLink = None):
        self._database = database
        self._keyChain = keyChain
        self._face = face
        self._groupName = Name(groupName)
        self._consumerName = Name(consumerName)
        self._cKeyLink = (Consumer.NO_LINK if cKeyLink == None
                          else Link(cKeyLink))
        self._dKeyLink = (Consumer.NO_LINK if dKeyLink == None
                          else Link(dKeyLink))

        # The dictionary key is the C-KEY name. The value is the encoded key Blob.
        self._cKeyMap = {}
        # The dictionary key is the D-KEY name. The value is the encoded key Blob.
        self._dKeyMap = {}

    def consume(self, contentName, onConsumeComplete, onError, link = None):
        """
        Express an Interest to fetch the content packet with contentName, and
        decrypt it, fetching keys as needed.

        :param Name contentName: The name of the content packet.
        :param onConsumeComplete: When the content packet is fetched and
          decrypted, this calls onConsumeComplete(contentData, result) where
          contentData is the fetched Data packet and result is the decrypted
          plain text Blob.
          NOTE: The library will log any exceptions raised by this callback, but
          for better error handling the callback should catch and properly
          handle any exceptions.
        :type onPlainText: function object
        :param onError: This calls onError(errorCode, message) for an error,
          where errorCode is from EncryptError.ErrorCode and message is a str.
          NOTE: The library will log any exceptions raised by this callback, but
          for better error handling the callback should catch and properly
          handle any exceptions.
        :type onError: function object
        :param Link link: (optional) The Link object to use in Interests for
          data retrieval. This makes a copy of the Link object. If the Link
          object's getDelegations().size() is zero, don't use it. If omitted,
          don't use a Link object.
        """
        if link == None:
            link = Consumer.NO_LINK

        interest = Interest(contentName)
        def onVerified(validData):
            # Decrypt the content.
            def onPlainText(plainText):
                try:
                    onConsumeComplete(validData, plainText)
                except:
                    logging.exception("Error in onConsumeComplete")
            self._decryptContent(validData, onPlainText, onError)
        # Copy the Link object since the passed link may become invalid.
        self._sendInterest(interest, 1, Link(link), onVerified, onError)

    def setGroup(self, groupName):
        """
        Set the group name.

        :param Name groupName: The reading group name that the consumer belongs
          to. This makes a copy of the Name.
        """
        self._groupName = Name(groupName)

    def addDecryptionKey(self, keyName, keyBlob):
        """
        Add a new decryption key with keyName and keyBlob to the database.

        :param Name keyName: The key name.
        :param Blob keyBlob: The encoded key.
        :raises ConsumerDb.Error: If a key with the same keyName already exists
          in the database, or other database error.
        :raises RuntimeError: if the consumer name is not a prefix of the key name.
        """
        if not self._consumerName.match(keyName):
            raise RuntimeError(
              "addDecryptionKey: The consumer name must be a prefix of the key name")
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例4: Node

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import match [as 别名]
class Node(object):
    """
    Create a new Node for communication with an NDN hub with the given Transport
    object and connectionInfo.

    :param Transport transport: An object of a subclass of Transport used for
      communication.
    :param Transport.ConnectionInfo connectionInfo: An object of a subclass of
      Transport.ConnectionInfo to be used to connect to the transport.
    """
    def __init__(self, transport, connectionInfo):
        self._transport = transport
        self._connectionInfo = connectionInfo
        # An array of _PendingInterest
        self._pendingInterestTable = []
        # An array of _RegisteredPrefix
        self._registeredPrefixTable = []
        # An array of _InterestFilterEntry
        self._interestFilterTable = []
        # An array of _DelayedCall
        self._delayedCallTable = []
        # An array of function objects
        self._onConnectedCallbacks = []
        self._ndndIdFetcherInterest = Interest(
          Name("/%C1.M.S.localhost/%C1.M.SRV/ndnd/KEY"))
        self._ndndIdFetcherInterest.setInterestLifetimeMilliseconds(4000.0)
        self._ndndId = None
        self._commandInterestGenerator = CommandInterestGenerator()
        self._timeoutPrefix = Name("/local/timeout")
        self._lastEntryId = 0
        self._lastEntryIdLock = threading.Lock()
        self._connectStatus = Node._ConnectStatus.UNCONNECTED

    def expressInterest(
      self, pendingInterestId, interestCopy, onData, onTimeout, wireFormat, face):
        """
        Send the Interest through the transport, read the entire response and
        call onData(interest, data).

        :param int pendingInterestId: The getNextEntryId() for the pending
          interest ID which Face got so it could return it to the caller.
        :param Interest interestCopy: The Interest which is NOT copied for this
          internal Node method.  The Face expressInterest is responsible for
          making a copy for Node to use.
        :param onData: A function object to call when a matching data packet is
          received.
        :type onData: function object
        :param onTimeout: A function object to call if the interest times out.
          If onTimeout is None, this does not use it.
        :type onTimeout: function object
        :param wireFormat: A WireFormat object used to encode the message.
        :type wireFormat: a subclass of WireFormat
        :param Face face: The face which has the callLater method, used for
          interest timeouts. The callLater method may be overridden in a
          subclass of Face.
        :throws: RuntimeError If the encoded interest size exceeds
          getMaxNdnPacketSize().
        """
        # TODO: Properly check if we are already connected to the expected host.
        if self._connectStatus == self._ConnectStatus.CONNECT_COMPLETE:
            # We are connected. Simply send the interest.
            self._expressInterestHelper(
              pendingInterestId, interestCopy, onData, onTimeout, wireFormat,
              face)
            return

        if self._connectStatus == Node._ConnectStatus.UNCONNECTED:
            self._connectStatus = Node._ConnectStatus.CONNECT_REQUESTED

            # expressInterestHelper will be called by onConnected.
            self._onConnectedCallbacks.append(
              lambda: self._expressInterestHelper
                (pendingInterestId, interestCopy, onData, onTimeout, wireFormat,
                 face))

            def onConnected():
                # Assume that further calls to expressInterest dispatched to the
                # event loop are queued and won't enter expressInterest until
                # this method completes and sets CONNECT_COMPLETE.
                # Call each callback added while the connection was opening.
                for onConnectedCallback in self._onConnectedCallbacks:
                    onConnectedCallback()
                self._onConnectedCallbacks = []

                # Make future calls to expressInterest send directly to the
                # Transport.
                self._connectStatus = Node._ConnectStatus.CONNECT_COMPLETE
                    
            self._transport.connect(self._connectionInfo, self, onConnected)
        elif self._connectStatus == self._ConnectStatus.CONNECT_REQUESTED:
            # Still connecting. add to the interests to express by onConnected.
            self._onConnectedCallbacks.append(
              lambda: self._expressInterestHelper
                (pendingInterestId, interestCopy, onData, onTimeout, wireFormat,
                 face))
        else:
            # Don't expect this to happen.
            raise RuntimeError(
              "Node: Unrecognized _connectStatus " + str(self._connectStatus))

#.........这里部分代码省略.........
开发者ID:mjycom,项目名称:PyNDN2,代码行数:103,代码来源:node.py

示例5: Node

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import match [as 别名]
class Node(object):
    """
    Create a new Node for communication with an NDN hub with the given Transport
    object and connectionInfo.

    :param Transport transport: An object of a subclass of Transport used for
      communication.
    :param Transport.ConnectionInfo connectionInfo: An object of a subclass of
      Transport.ConnectionInfo to be used to connect to the transport.
    """
    def __init__(self, transport, connectionInfo):
        self._transport = transport
        self._connectionInfo = connectionInfo
        # An array of PendintInterest
        self._pendingInterestTable = []
        # An array of RegisteredPrefix
        self._registeredPrefixTable = []
        self._ndndIdFetcherInterest = Interest(
          Name("/%C1.M.S.localhost/%C1.M.SRV/ndnd/KEY"))
        self._ndndIdFetcherInterest.setInterestLifetimeMilliseconds(4000.0)
        self._ndndId = None
        self._commandInterestGenerator = CommandInterestGenerator()
        self._timeoutPrefix = Name("/local/timeout")

    def expressInterest(self, interest, onData, onTimeout, wireFormat):
        """
        Send the Interest through the transport, read the entire response and
        call onData(interest, data).

        :param Interest interest: The Interest which is NOT copied for this
          internal Node method.  The Face expressInterest is reponsible for
          making a copy for Node to use.
        :param onData: A function object to call when a matching data packet is
          received.
        :type onData: function object
        :param onTimeout: A function object to call if the interest times out.
          If onTimeout is None, this does not use it.
        :type onTimeout: function object
        :param wireFormat: A WireFormat object used to encode the message.
        :type wireFormat: a subclass of WireFormat
        """
        # TODO: Properly check if we are already connected to the expected host.
        if not self._transport.getIsConnected():
            self._transport.connect(self._connectionInfo, self)

        pendingInterestId = Node._PendingInterest.getNextPendingInterestId()
        self._pendingInterestTable.append(
          Node._PendingInterest(pendingInterestId, interest, onData,
                          onTimeout))

        # Special case: For _timeoutPrefix we don't actually send the interest.
        if not self._timeoutPrefix.match(interest.getName()):
          self._transport.send(interest.wireEncode(wireFormat).toBuffer())

        return pendingInterestId

    def removePendingInterest(self, pendingInterestId):
        """
        Remove the pending interest entry with the pendingInterestId from the
        pending interest table. This does not affect another pending interest
        with a different pendingInterestId, even if it has the same interest
        name. If there is no entry with the pendingInterestId, do nothing.

        :param int pendingInterestId: The ID returned from expressInterest.
        """
        # Go backwards through the list so we can erase entries.
        # Remove all entries even though pendingInterestId should be unique.
        i = len(self._pendingInterestTable) - 1
        while i >= 0:
            if (self._pendingInterestTable[i].getPendingInterestId() ==
                  pendingInterestId):
                self._pendingInterestTable.pop(i)
            i -= 1

    def makeCommandInterest(self, interest, keyChain, certificateName, wireFormat):
        """
        Append a timestamp component and a random value component to interest's
        name. Then use the keyChain and certificateName to sign the interest.
        If the interest lifetime is not set, this sets it.

        :param Interest interest: The interest whose name is append with
          components.
        :param KeyChain keyChain: The KeyChain for calling sign.
        :param Name certificateName: The certificate name of the key to use for
          signing.
        :param wireFormat: A WireFormat object used to encode the
          SignatureInfo and to encode the interest name for signing.
        :type wireFormat: A subclass of WireFormat
        """
        self._commandInterestGenerator.generate(
          interest, keyChain, certificateName, wireFormat)

    def registerPrefix(
      self, prefix, onInterest, onRegisterFailed, flags, wireFormat,
      commandKeyChain, commandCertificateName):
        """
        Register prefix with the connected NDN hub and call onInterest when a
        matching interest is received.

        :param Name prefix: The Name for the prefix to register which is NOT
#.........这里部分代码省略.........
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:103,代码来源:node.py


注:本文中的pyndn.name.Name.match方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。