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


Python Name.append方法代码示例

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


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

示例1: produce

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def produce(self, data, timeSlot, content, onError=defaultOnError):
        """
        Encrypt the given content with the content key that covers timeSlot, and
        update the data packet with the encrypted content and an appropriate
        data name.

        :param Data data: An empty Data object which is updated.
        :param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC.
        :param Blob content: The content to encrypt.
        :param onError: (optional) This calls onError(errorCode, message) for an
          error, where errorCode is from EncryptError.ErrorCode and message is a
          str. If omitted, use a default callback which does nothing.
          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
        """
        # Get a content key.
        contentKeyName = self.createContentKey(timeSlot, None, onError)
        contentKey = self._database.getContentKey(timeSlot)

        # Produce data.
        dataName = Name(self._namespace)
        dataName.append(Schedule.toIsoString(timeSlot))

        data.setName(dataName)
        params = EncryptParams(EncryptAlgorithmType.AesCbc, 16)
        Encryptor.encryptData(data, content, contentKeyName, contentKey, params)
        self._keyChain.sign(data)
开发者ID:named-data,项目名称:PyNDN2,代码行数:31,代码来源:producer.py

示例2: _initialTimeOut

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _initialTimeOut(self, interest):
        """
        Initial sync interest timeout, which means there are no other publishers
        yet.
        """
        if not self._enabled:
            # Ignore callbacks after the application calls shutdown().
            return

        logging.getLogger(__name__).info("initial sync timeout")
        logging.getLogger(__name__).info("no other people")
        self._sequenceNo += 1
        if self._sequenceNo != 0:
            # Since there were no other users, we expect sequence no 0.
            raise RuntimeError(
              "ChronoSync: sequenceNo_ is not the expected value of 0 for first use.")

        tempContent = sync_state_pb2.SyncStateMsg()
        content = getattr(tempContent, "ss").add()
        content.name = self._applicationDataPrefixUri
        content.type = SyncState_UPDATE
        content.seqno.seq = self._sequenceNo
        content.seqno.session = self._sessionNo
        self._update(getattr(tempContent, "ss"))

        self._onInitialized()

        name = Name(self._applicationBroadcastPrefix)
        name.append(self._digestTree.getRoot())
        retryInterest = Interest(name)
        retryInterest.setInterestLifetimeMilliseconds(self._syncLifetime)
        self._face.expressInterest(retryInterest, self._onData, self._syncTimeout)
        logging.getLogger(__name__).info("Syncinterest expressed:")
        logging.getLogger(__name__).info("%s", name.toUri())
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:36,代码来源:chrono_sync2013.py

示例3: _createDKeyData

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _createDKeyData(self, startTimeStamp, endTimeStamp, keyName,
                        privateKeyBlob, certificateKey):
        """
        Create a D-KEY Data packet with an EncryptedContent for the given
        private key, encrypted with the certificate key.

        :param str startTimeStamp: The start time stamp string to put in the name.
        :param str endTimeStamp: The end time stamp string to put in the name.
        :param Name keyName The key name to put in the data packet name and the
          EncryptedContent key locator.
        :param Blob privateKeyBlob: A Blob of the encoded private key.
        :param Blob certificateKey: The certificate key encoding, used to
          encrypt the private key.
        :return: The Data packet.
        :rtype: Data
        """
        name = Name(self._namespace)
        name.append(Encryptor.NAME_COMPONENT_D_KEY)
        name.append(startTimeStamp).append(endTimeStamp)
        data = Data(name)
        data.getMetaInfo().setFreshnessPeriod(
          self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR)
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        Encryptor.encryptData(
          data, privateKeyBlob, keyName, certificateKey, encryptParams)
        self._keyChain.sign(data)
        return data
开发者ID:named-data,项目名称:PyNDN2,代码行数:29,代码来源:group_manager.py

示例4: _onData

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _onData(self, interest, data):
        """
        Process Sync Data.
        """
        if not self._enabled:
            # Ignore callbacks after the application calls shutdown().
            return

        logging.getLogger(__name__).info(
          "Sync ContentObject received in callback")
        logging.getLogger(__name__).info(
            "name: %s", data.getName().toUri())
        # TODO: Check if this works in Python 3.
        tempContent = SyncStateMsg()
#pylint: disable=E1103
        tempContent.ParseFromString(data.getContent().toBytes())
#pylint: enable=E1103
        content = getattr(tempContent, "ss")
        if self._digestTree.getRoot() == "00":
            isRecovery = True
            #processing initial sync data
            self._initialOndata(content)
        else:
            self._update(content)
            if (interest.getName().size() ==
                self._applicationBroadcastPrefix.size() + 2):
                # Assume this is a recovery interest.
                isRecovery = True
            else:
                isRecovery = False

        # Send the interests to fetch the application data.
        syncStates = []
        for i in range(len(content)):
            syncState = content[i]

            # Only report UPDATE sync states.
            if syncState.type == SyncState_UPDATE:
                if len(syncState.application_info) > 0:
                    applicationInfo = Blob(syncState.application_info, True)
                else:
                    applicationInfo = Blob()

                syncStates.append(self.SyncState(
                  syncState.name, syncState.seqno.session,
                  syncState.seqno.seq, applicationInfo))

        try:
            self._onReceivedSyncState(syncStates, isRecovery)
        except:
            logging.exception("Error in onReceivedSyncState")

        name = Name(self._applicationBroadcastPrefix)
        name.append(self._digestTree.getRoot())
        syncInterest = Interest(name)
        syncInterest.setInterestLifetimeMilliseconds(self._syncLifetime)
        self._face.expressInterest(syncInterest, self._onData, self._syncTimeout)
        logging.getLogger(__name__).info("Syncinterest expressed:")
        logging.getLogger(__name__).info("%s", name.toUri())
开发者ID:named-data,项目名称:PyNDN2,代码行数:61,代码来源:chrono_sync2013.py

示例5: _sendRecovery

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
 def _sendRecovery(self, syncDigest):
     """
     Send Recovery Interest.
     """
     logging.getLogger(__name__).info("unknown digest: ")
     name = Name(self._applicationBroadcastPrefix)
     name.append("recovery").append(syncDigest)
     interest = Interest(name)
     interest.setInterestLifetimeMilliseconds(self._syncLifetime)
     self._face.expressInterest(interest, self._onData, self._syncTimeout)
     logging.getLogger(__name__).info("Recovery Syncinterest expressed:")
     logging.getLogger(__name__).info("%s", name.toUri())
开发者ID:named-data,项目名称:PyNDN2,代码行数:14,代码来源:chrono_sync2013.py

示例6: constructKeyName

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def constructKeyName(identityName, keyId):
        """
        Construct a key name based on the appropriate naming conventions.

        :param Name identityName: The name of the identity.
        :param Name.Component keyId: The key ID name component.
        :return: The constructed name as a new Name.
        :rtype: Name
        """
        keyName = Name(identityName)
        keyName.append(CertificateV2.KEY_COMPONENT).append(keyId)

        return keyName
开发者ID:named-data,项目名称:PyNDN2,代码行数:15,代码来源:pib_key.py

示例7: __init__

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def __init__(self, prefix, dataType, face, keyChain, database, repeatAttempts=None, keyRetrievalLink=None):
        self._face = face
        self._keyChain = keyChain
        self._database = database
        self._maxRepeatAttempts = 3 if repeatAttempts == None else repeatAttempts
        self._keyRetrievalLink = Producer.NO_LINK if keyRetrievalLink == None else Link(keyRetrievalLink)

        # The dictionary key is the key Name The value is a Producer._KeyInfo.
        self._eKeyInfo = {}
        # The dictionary key is the float time stamp. The value is a Producer._KeyRequest.
        self._keyRequests = {}

        fixedPrefix = Name(prefix)
        fixedDataType = Name(dataType)

        # Fill _ekeyInfo with all permutations of dataType, including the 'E-KEY'
        # component of the name. This will be used in createContentKey to send
        # interests without reconstructing names every time.
        fixedPrefix.append(Encryptor.NAME_COMPONENT_READ)
        while fixedDataType.size() > 0:
            nodeName = Name(fixedPrefix)
            nodeName.append(fixedDataType)
            nodeName.append(Encryptor.NAME_COMPONENT_E_KEY)

            self._eKeyInfo[nodeName] = Producer._KeyInfo()
            fixedDataType = fixedDataType.getPrefix(-1)

        fixedPrefix.append(dataType)
        self._namespace = Name(prefix)
        self._namespace.append(Encryptor.NAME_COMPONENT_SAMPLE)
        self._namespace.append(dataType)
开发者ID:named-data,项目名称:PyNDN2,代码行数:33,代码来源:producer.py

示例8: _makeSelfSignedCertificate

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _makeSelfSignedCertificate(
      keyName, privateKeyBag, publicKeyEncoding, password, digestAlgorithm,
      wireFormat):
        certificate = CertificateV2()

        # Set the name.
        now = Common.getNowMilliseconds()
        certificateName = Name(keyName)
        certificateName.append("self").appendVersion(int(now))
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # Set a one-hour freshness period.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        publicKey = PublicKey(publicKeyEncoding)
        certificate.setContent(publicKey.getKeyDer())

        # Create a temporary in-memory Tpm and import the private key.
        tpm = Tpm("", "", TpmBackEndMemory())
        tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password)

        # Set the signature info.
        if publicKey.getKeyType() == KeyType.RSA:
            certificate.setSignature(Sha256WithRsaSignature())
        elif publicKey.getKeyType() == KeyType.EC:
            certificate.setSignature(Sha256WithEcdsaSignature())
        else:
            raise ValueError("Unsupported key type")
        signatureInfo = certificate.getSignature()
        KeyLocator.getFromSignature(signatureInfo).setType(KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName)

        # Set a 20-year validity period.
        ValidityPeriod.getFromSignature(signatureInfo).setPeriod(
          now, now + 20 * 365 * 24 * 3600 * 1000.0)

        # Encode once to get the signed portion.
        encoding = certificate.wireEncode(wireFormat)
        signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName,
          digestAlgorithm)
        signatureInfo.setSignature(signatureBytes)

        # Encode again to include the signature.
        certificate.wireEncode(wireFormat)

        return certificate
开发者ID:named-data,项目名称:PyNDN2,代码行数:51,代码来源:safe_bag.py

示例9: _encryptContentKey

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _encryptContentKey(self, encryptionKey, eKeyName, timeSlot,
                           onEncryptedKeys, onError):
        """
        Get the content key from the database_ and encrypt it for the timeSlot
          using encryptionKey.

        :param Blob encryptionKey: The encryption key value.
        :param Name eKeyName: The key name for the EncryptedContent.
        :param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC.
        :param onEncryptedKeys: When there are no more interests to process,
           this calls onEncryptedKeys(keys) where keys is a list of encrypted
           content key Data packets. If onEncryptedKeys is None, this does not
           use it.
        :type onEncryptedKeys: function object
        :param onError: This calls onError(errorCode, message) for an error.
        :type onError: function object
        :return: True if encryption succeeds, otherwise False.
        :rtype: bool
        """
        timeCount = round(timeSlot)
        keyRequest = self._keyRequests[timeCount]

        keyName = Name(self._namespace)
        keyName.append(Encryptor.NAME_COMPONENT_C_KEY)
        keyName.append(
          Schedule.toIsoString(Producer._getRoundedTimeSlot(timeSlot)))

        contentKey = self._database.getContentKey(timeSlot)

        cKeyData = Data()
        cKeyData.setName(keyName)
        params = EncryptParams(EncryptAlgorithmType.RsaOaep)
        try:
            Encryptor.encryptData(
              cKeyData, contentKey, eKeyName, encryptionKey, params)
        except Exception as ex:
            try:
                onError(EncryptError.ErrorCode.EncryptionFailure,
                        "encryptData error: " + repr(ex))
            except:
                logging.exception("Error in onError")
            return False

        self._keyChain.sign(cKeyData)
        keyRequest.encryptedKeys.append(cKeyData)
        self._updateKeyRequest(keyRequest, timeCount, onEncryptedKeys)
        return True
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:49,代码来源:producer.py

示例10: _decryptCKey

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _decryptCKey(self, cKeyData, onPlainText, onError):
        """
        Decrypt cKeyData.

        :param Data cKeyData: The C-KEY data packet.
        :param onPlainText: When the data packet is decrypted, this calls
          onPlainText(decryptedBlob) with the decrypted blob.
        :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.
        :type onError: function object
        """
        # Get the encrypted content.
        cKeyContent = cKeyData.getContent()
        cKeyEncryptedContent = EncryptedContent()
        try:
            cKeyEncryptedContent.wireDecode(cKeyContent)
        except Exception as ex:
            try:
                onError(EncryptError.ErrorCode.InvalidEncryptedFormat, repr(ex))
            except:
                logging.exception("Error in onError")
            return
        eKeyName = cKeyEncryptedContent.getKeyLocator().getKeyName()
        dKeyName = eKeyName.getPrefix(-3)
        dKeyName.append(Encryptor.NAME_COMPONENT_D_KEY).append(
          eKeyName.getSubName(-2))

        # Check if the decryption key is already in the store.
        if dKeyName in self._dKeyMap:
            dKey = self._dKeyMap[dKeyName]
            Consumer._decrypt(cKeyEncryptedContent, dKey, onPlainText, onError)
        else:
            # Get the D-Key Data.
            interestName = Name(dKeyName)
            interestName.append(Encryptor.NAME_COMPONENT_FOR).append(
              self._consumerName)
            interest = Interest(interestName)

            def onVerified(validDKeyData):
                def localOnPlainText(dKeyBits):
                    # dKeyName is already a local copy.
                    self._dKeyMap[dKeyName] = dKeyBits
                    Consumer._decrypt(
                      cKeyEncryptedContent, dKeyBits, onPlainText, onError)
                self._decryptDKey(validDKeyData, localOnPlainText, onError)
            self._sendInterest(interest, 1, self._dKeyLink, onVerified, onError)
开发者ID:,项目名称:,代码行数:49,代码来源:

示例11: _sendSyncData

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _sendSyncData(self, name, content):
        """
        Send the sync Data. Check if the data will satisfy our own pending
        Interest. If it does, then remove it and then renew the sync interest.
        Otherwise, just send the Data.

        :param Name name: The basis to use for the Data name.
        :param Blob content: The content of the Data.
        """
        logging.getLogger(__name__).debug(
          "Checking if the Data will satisfy our own pending interest")

        nameWithIblt = Name()
        nameWithIblt.append(self._iblt.encode())

        # Append the hash of our IBLT so that the Data name should be different
        # for each node. Use abs() since hash() can return negative.
        dataName = Name(name).appendNumber(abs(hash(nameWithIblt)))

        # Check if our own Interest got satisfied.
        if self._outstandingInterestName.equals(name):
            logging.getLogger(__name__).debug("Satisfies our own pending Interest")
            # Remove the outstanding interest.
            # Debug: Implement stopping an ongoing fetch.
            #if self._fetcher != None:
            #    logging.getLogger(__name__).debug(
            #      "Removing our pending interest from the Face (stopping fetcher)")
            #    self._fetcher.stop()
            #    self._outstandingInterestName = Name()
            self._outstandingInterestName = Name()

            logging.getLogger(__name__).debug("Sending sync Data")

            # Send Data after removing the pending sync interest on the Face.
            self._segmentPublisher.publish(
              name, dataName, content, self._syncReplyFreshnessPeriod,
              self._signingInfo)

            logging.getLogger(__name__).info("sendSyncData: Renewing sync interest")
            self._sendSyncInterest()
        else:
            logging.getLogger(__name__).debug(
              "Sending Sync Data for not our own Interest")
            self._segmentPublisher.publish(
              name, dataName, content, self._syncReplyFreshnessPeriod,
              self._signingInfo)
开发者ID:named-data,项目名称:PyNDN2,代码行数:48,代码来源:full_psync2017.py

示例12: toName

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def toName(componentArray):
        """
        Return a Name made from the component array in a Protobuf message object,
        assuming that it was defined with "repeated bytes". For example:
        message Name {
        repeated bytes component = 8;
        }

        :param Array componentArray: The array from the Protobuf message object
          representing the "repeated bytes" component array.
        :return: A new Name.
        :rtype: Name
        """
        name = Name()
        for component in componentArray:
            name.append(Blob(component, True))

        return name
开发者ID:named-data,项目名称:PyNDN2,代码行数:20,代码来源:protobuf_tlv.py

示例13: _createEKeyData

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _createEKeyData(self, startTimeStamp, endTimeStamp, publicKeyBlob):
        """
        Create an E-KEY Data packet for the given public key.

        :param str startTimeStamp: The start time stamp string to put in the name.
        :param str endTimeStamp: The end time stamp string to put in the name.
        :param Blob publicKeyBlob: A Blob of the public key DER.
        :return: The Data packet.
        :rtype: Data
        """
        name = Name(self._namespace)
        name.append(Encryptor.NAME_COMPONENT_E_KEY).append(startTimeStamp).append(endTimeStamp)

        data = Data(name)
        data.getMetaInfo().setFreshnessPeriod(self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR)
        data.setContent(publicKeyBlob)
        self._keyChain.sign(data)
        return data
开发者ID:named-data,项目名称:PyNDN2,代码行数:20,代码来源:group_manager.py

示例14: _decryptContent

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _decryptContent(self, data, onPlainText, onError):
        """
        Decrypt the data packet.

        :param Data data: The data packet. This does not verify the packet.
        :param onPlainText: When the data packet is decrypted, this calls
          onPlainText(decryptedBlob) with the decrypted blob.
        :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.
        :type onError: function object
        """
        # Get the encrypted content.
        dataEncryptedContent = EncryptedContent()
        try:
            dataEncryptedContent.wireDecode(data.getContent())
        except Exception as ex:
            Consumer._callOnError(onError,
              EncryptError.ErrorCode.InvalidEncryptedFormat, repr(ex))
            return
        cKeyName = dataEncryptedContent.getKeyLocator().getKeyName()

        # Check if the content key is already in the store.
        if cKeyName in self._cKeyMap:
            cKey = self._cKeyMap[cKeyName]
            self._decrypt(dataEncryptedContent, cKey, onPlainText, onError)
        else:
            # Retrieve the C-KEY Data from the network.
            interestName = Name(cKeyName)
            interestName.append(Encryptor.NAME_COMPONENT_FOR).append(self._groupName)
            interest = Interest(interestName)

            def onVerified(validCKeyData):
                def localOnPlainText(cKeyBits):
                   # cKeyName is already a copy inside the local
                   #   dataEncryptedContent.
                   self._cKeyMap[cKeyName] = cKeyBits
                   Consumer._decrypt(
                     dataEncryptedContent, cKeyBits, onPlainText, onError)
                self._decryptCKey(validCKeyData, localOnPlainText, onError)
            self._sendInterest(interest, 1, self._cKeyLink, onVerified, onError)
开发者ID:,项目名称:,代码行数:43,代码来源:

示例15: _sendSyncInterest

# 需要导入模块: from pyndn.name import Name [as 别名]
# 或者: from pyndn.name.Name import append [as 别名]
    def _sendSyncInterest(self):
        """
        Send the sync interest for full synchronization. This forms the interest
        name: /<sync-prefix>/<own-IBLT>. This cancels any pending sync interest
        we sent earlier on the face.
        """
        # Debug: Implement stopping an ongoing fetch.
        ## If we send two sync interest one after the other
        ## since there is no new data in the network yet,
        ## when data is available it may satisfy both of them
        #if self._fetcher != None:
        #    self._fetcher.stop()

        # Sync Interest format for full sync: /<sync-prefix>/<ourLatestIBF>
        syncInterestName = Name(self._syncPrefix)

        # Append our latest IBLT.
        syncInterestName.append(self._iblt.encode())

        self._outstandingInterestName = syncInterestName

        # random1 is from 0.0 to 1.0.
        random1 = self._systemRandom.random()
        # Get a jitter of +/- syncInterestLifetime_ * 0.2 .
        jitter = (random1 - 0.5) * (self._syncInterestLifetime * 0.2)

        self._face.callLater(
          self._syncInterestLifetime / 2 + jitter, self._sendSyncInterest)

        syncInterest = Interest(syncInterestName)
        syncInterest.setInterestLifetimeMilliseconds(self._syncInterestLifetime)
        syncInterest.refreshNonce()

        SegmentFetcher.fetch(
          self._face, syncInterest, None,
          lambda content: self._onSyncData(content, syncInterest),
          FullPSync2017._onError)

        logging.getLogger(__name__).debug("sendFullSyncInterest, nonce: " +
          syncInterest.getNonce().toHex() + ", hash: " +
          str(abs(hash(syncInterestName))))
开发者ID:named-data,项目名称:PyNDN2,代码行数:43,代码来源:full_psync2017.py


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