本文整理汇总了Python中pyndn.Data.getName方法的典型用法代码示例。如果您正苦于以下问题:Python Data.getName方法的具体用法?Python Data.getName怎么用?Python Data.getName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Data
的用法示例。
在下文中一共展示了Data.getName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: onInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onInterest(self, prefix, interest, transport, registeredPrefixId):
print "received interest"
initInterest = Name(interest.getName())
print "interest name:",initInterest.toUri()
d = Data(interest.getName().append(self.deviceComponent))
try:
print "start to set data's content"
currentString = ','.join(currentList)
d.setContent("songList of " +self.device+":"+currentString+ "\n")
self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
self.keychain.sign(d,self.certificateName)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
self.loop.close()
self.face.shutdown()
self.face = None
示例2: onInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onInterest(self, prefix, interest, transport, registeredPrefixId):
print "received interest"
initInterest = Name(interest.getName())
print "interest name:",initInterest.toUri()
#d = Data(interest.getName().getPrefix(prefix.size()+1))
#self.excludeDevice = interest.getName().get(prefix.size())
#initInterest = interest.getName()
d = Data(interest.getName().append(self.deviceComponent))
try:
if(initInterest == self.prefix):
print "start to set data's content"
currentString = ','.join(currentList)
d.setContent("songList of " +self.device+":"+currentString+ "\n")
else:
self.excludeDevice = initInterest.get(prefix.size())
print "excludeDevice",self.excludeDevice.toEscapedString()
if(self.excludeDevice != self.deviceComponent):
print "start to set data's content"
currentString = ','.join(currentList)
d.setContent("songList of " +self.device+":"+currentString+ "\n")
else:
print"remove register"
self.face.removeRegisteredPrefix(registeredPrefixId)
time.sleep(30)
#sleep 30s which means user cannot update the song list twice within 1 minutes
print"register again"
self.face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
self.keychain.sign(d,self.certificateName)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
示例3: onInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onInterest(self, prefix, interest, transport, registeredPrefixId):
initInterest = Name(interest.getName())
print "interest name:",initInterest.toUri()
d = Data(interest.getName().append(self.deviceComponent))
try:
if(initInterest == self.listPrefix):
print "initial db,start to set data's content"
currentString = ','.join(currentList)
d.setContent(currentString)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
else:
self.excludeDevice = initInterest.get(self.listPrefix.size())
excDevice = self.excludeDevice.toEscapedString()
if(excDevice != str("exc")+self.device):
print "not init db,start to set data's content"
currentString = ','.join(currentList)
d.setContent(currentString)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
else:
print"controller has exclude me, I have to remove register!!!!!!!"
self.face.removeRegisteredPrefix(registeredPrefixId)
print"register again"
self.face.registerPrefix(self.listPrefix,self.onInterest,self.onRegisterFailed)
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
self.keychain.sign(d,self.certificateName)
示例4: run
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def run(self):
print 'Simple KDS start'
# Publish sym key
keyid = hashlib.sha256(self.usr_key.publickey().exportKey("DER")).digest()
cipher = PKCS1_v1_5.new(self.usr_key)
ciphertext = cipher.encrypt(self.symkey)
symkey_name = self.prefix.append(bytearray(self.timestamp)).append(bytearray(keyid))
symkey_data = Data(symkey_name)
symkey_data.setContent(bytearray(ciphertext))
self.keychain.sign(symkey_data, self.cert_name)
self.publisher.put(symkey_data)
print symkey_data.getName().toUri()
print 'Simple KDS stop'
示例5: generateData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def generateData(self, baseName):
'''
This appends the segment number to the data name, since repo-ng tends to expect it
'''
# just make up some data and return it
ts = (time.time())
segmentId = 0 # compatible with repo-ng test: may change to test segmented data
versionStr = baseName.get(-1).toEscapedString()
dataName = Name(baseName)
dataName.appendSegment(segmentId)
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
d.getMetaInfo().setFreshnessPeriod(-1)
if shouldSign:
self.keychain.sign(d, self.certificateName)
else:
d.setSignature(self.fakeSignature)
stats.insertDataForVersion(versionStr, {'publish_time':time.time()})
logger.debug('Publishing: '+d.getName().toUri())
return d
示例6: main
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def main():
data = Data()
data.wireDecode(TlvData)
# Use a hard-wired secret for testing. In a real application the signer
# ensures that the verifier knows the shared key and its keyName.
key = Blob(bytearray([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
]))
if KeyChain.verifyDataWithHmacWithSha256(data, key):
dump("Hard-coded data signature verification: VERIFIED")
else:
dump("Hard-coded data signature verification: FAILED")
freshData = Data(Name("/ndn/abc"))
signature = HmacWithSha256Signature()
signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
signature.getKeyLocator().setKeyName(Name("key1"))
freshData.setSignature(signature)
freshData.setContent("SUCCESS!")
dump("Signing fresh data packet", freshData.getName().toUri())
KeyChain.signWithHmacWithSha256(freshData, key)
if KeyChain.verifyDataWithHmacWithSha256(freshData, key):
dump("Freshly-signed data signature verification: VERIFIED")
else:
dump("Freshly-signed data signature verification: FAILED")
示例7: publishData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def publishData(self):
timestamp = time.time()
info = {''}
if self._pir == None:
cpu_use = ps.cpu_percent()
users = [u.name for u in ps.users()]
nProcesses = len(ps.pids())
memUse = ps.virtual_memory().percent
swapUse = ps.swap_memory().percent
info = {'count': self._count, 'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses,
'memory_usage':memUse, 'swap_usage':swapUse}
else:
info = {'count': self._count, 'pir_bool': self._pir.read()}
self._count += 1
dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp)))
dataOut.setContent(json.dumps(info))
dataOut.getMetaInfo().setFreshnessPeriod(10000)
self.signData(dataOut)
#self._dataCache.add(dataOut)
# instead of adding data to content cache, we put data to nfd anyway
self.send(dataOut.wireEncode().buf())
print('data name: ' + dataOut.getName().toUri() + '; content: ' + str(info))
# repeat every 1 seconds
self.loop.call_later(1, self.publishData)
示例8: createData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def createData(self, namePrefix, timestamp, payload, certName):
data = Data(Name(self._namespace).append(namePrefix).append(str(int(float(timestamp)))))
data.setContent(payload)
self._keyChain.sign(data, certName)
data.getMetaInfo().setFreshnessPeriod(self.DEFAULT_DATA_LIFETIME)
if __debug__:
print(data.getName().toUri())
return data
示例9: onData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onData(self, interest, data):
print data.getName().toUri()
usr_pubkey = str(bytearray(data.getContent().toBuffer()))
# Publish sym key
usrkey = RSA.importKey(usr_pubkey)
keyid = hashlib.sha256(usrkey.publickey().exportKey("DER")).digest()
cipher = PKCS1_v1_5.new(usrkey)
ciphertext = cipher.encrypt(self.symkey)
symkey_name = self.prefix.append(bytearray(self.timestamp)).append(bytearray(keyid))
symkey_data = Data(symkey_name)
symkey_data.setContent(bytearray(ciphertext))
self.keychain.sign(symkey_data, self.cert_name)
self.publisher.put(symkey_data)
print symkey_data.getName().toUri()
self.flag_terminate = 1
示例10: onReadPir
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onReadPir(self, interest):
# try to find a matching pir
pirInfo = next((pair[1] for pair in self._pirs.items()
if Name(pair[1]["device"]).match(interest.getName())), None)
if pirInfo is None:
data = Data(interest.getName())
data.setContent("MALFORMED COMMAND")
data.getMetaInfo().setFreshnessPeriod(1000) # 1 second, in milliseconds
return data
lastTime = pirInfo["lastTime"]
lastValue = pirInfo["lastVal"]
# If interest exclude doesn't match timestamp from last tx'ed data
# then resend data
if not interest.getExclude().matches(Name.Component(str(lastTime))):
print "Received interest without exclude ACK:", interest.getExclude().toUri()
print "\tprevious timestamp:", str(lastTime)
data = Data(Name(interest.getName()).append(str(lastTime)))
payload = { "pir" : lastValue}
content = json.dumps(payload)
data.setContent(content)
data.getMetaInfo().setFreshnessPeriod(1000) # 1 second, in milliseconds
print "Sent data:", data.getName().toUri(), "with content", content
return data
# otherwise, make new data
currentValue = pirInfo["device"].read()
timestamp = int(time.time() * 1000) # in milliseconds
pirInfo["lastTime"] = timestamp
pirInfo["lastVal"] = currentValue
data = Data(Name(interest.getName()).append(str(timestamp)))
payload = { "pir" : currentValue}
content = json.dumps(payload)
data.setContent(content)
data.getMetaInfo().setFreshnessPeriod(1000) # 1 second, in milliseconds
print "Sent data:", data.getName().toUri(), "with content", content
return data
示例11: contentCacheAddEntityData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def contentCacheAddEntityData(self, name, entityInfo):
content = self._serializer.serialize(entityInfo)
data = Data(Name(name))
data.setContent(content)
data.getMetaInfo().setFreshnessPeriod(self._entityDataFreshnessPeriod)
self._keyChain.sign(data, self._certificateName)
self._memoryContentCache.add(data)
print "added entity to cache: " + data.getName().toUri() + "; " + data.getContent().toRawStr()
示例12: test_full_name
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def test_full_name(self):
data = Data()
data.wireDecode(codedData)
# Check the full name format.
self.assertEqual(data.getFullName().size(), data.getName().size() + 1)
self.assertEqual(data.getName(), data.getFullName().getPrefix(-1))
self.assertEqual(data.getFullName().get(-1).getValue().size(), 32)
# Check the independent digest calculation.
sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend())
sha256.update(Blob(codedData).toBytes())
newDigest = Blob(bytearray(sha256.finalize()), False)
self.assertTrue(newDigest.equals(data.getFullName().get(-1).getValue()))
# Check the expected URI.
self.assertEqual(
data.getFullName().toUri(), "/ndn/abc/sha256digest=" +
"96556d685dcb1af04be4ae57f0e7223457d4055ea9b3d07c0d337bef4a8b3ee9")
# Changing the Data packet should change the full name.
saveFullName = Name(data.getFullName())
data.setContent(Blob())
self.assertNotEqual(data.getFullName().get(-1), saveFullName.get(-1))
示例13: publishData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def publishData(self, idx):
# Translation of the video URL has finished by the time of the publishData call;
# if not, we set translated to "publish"; this is data race free since translateUrl and publishData are scheduled in the same thread
if self._events[idx]["translated"] != "none":
# Order published events sequence numbers by start times in destination
data = Data(Name(self._namePrefixString + str(self._currentIdx)))
data.setContent(json.dumps(self._events[idx]))
data.getMetaInfo().setFreshnessPeriod(self._dataLifetime)
self._keyChain.sign(data, self._certificateName)
self._memoryContentCache.add(data)
self._currentIdx += 1
if __debug__:
eventId = str(self._events[idx]["event_id"])
channel = str(self._events[idx]["channel"])
srcUrl = str(self._events[idx]["src_url"])
clipName = str(self._events[idx]["clipName"])
ytPresent = str(self._events[idx]["ytPresent"])
clipStartTime = str(self._events[idx]["dst_start_time"])
clipEndTime = str(self._events[idx]["dst_end_time"])
print(
str(time.time())
+ " Added event ["
+ eventId
+ "-"
+ channel
+ "|"
+ clipName
+ " YT:"
+ ytPresent
+ " "
+ srcUrl[0:30]
+ "... "
+ clipStartTime
+ "-"
+ clipEndTime
+ "] ("
+ data.getName().toUri()
+ ")"
)
else:
self._events[idx]["translated"] = "publish"
示例14: onBtleData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def onBtleData(self, data):
# expect data format like "0.2,0.1,0.3"
content = data.getContent().toRawStr()
print "got data: " + data.getName().toUri() + " : " + content
if self._security:
# Hmac verify the data we receive
pass
pyr = content.split(',')
if len(pyr) >= 3:
resultingContent = "{\"p\":" + pyr[0] + ",\"y\":" + pyr[1] + ",\"r\":" + pyr[2] + "}"
timestamp = time.time() * 1000
dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp)))
dataOut.setContent(resultingContent)
dataOut.getMetaInfo().setFreshnessPeriod(10000)
self._keyChain.sign(dataOut, self._certificateName)
self._dataCache.add(dataOut)
print "data added: " + dataOut.getName().toUri()
示例15: publishData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import getName [as 别名]
def publishData(self):
timestamp = time.time()
cpu_use = ps.cpu_percent()
users = [u.name for u in ps.users()]
nProcesses = len(ps.pids())
memUse = ps.virtual_memory().percent
swapUse = ps.swap_memory().percent
info = {'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses,
'memory_usage':memUse, 'swap_usage':swapUse}
dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp)))
dataOut.setContent(json.dumps(info))
dataOut.getMetaInfo().setFreshnessPeriod(10000)
self._keyChain.sign(dataOut, self._certificateName)
self._dataCache.add(dataOut)
print "data added: " + dataOut.getName().toUri()
# repeat every 5 seconds
self._face.callLater(5000, self.publishData)