本文整理汇总了Python中pyndn.Data.setContent方法的典型用法代码示例。如果您正苦于以下问题:Python Data.setContent方法的具体用法?Python Data.setContent怎么用?Python Data.setContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Data
的用法示例。
在下文中一共展示了Data.setContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrap_content
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def wrap_content(self, name, content, key=None, key_locator=None):
"""
@param name - name of the data
@param content - data to be wrapped
@param key - key used to sign the data
@return the content object created
wraps the given name and content into a content object
"""
co = Data(Name(name))
co.setContent(content)
co.getMetaInfo().setFreshnessPeriod(5000)
co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
identityManager = IdentityManager(identityStorage, privateKeyStorage)
keyChain = KeyChain(identityManager, None)
# Initialize the storage.
keyName = Name("/ndn/bms/DSK-default")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(keyName, DEFAULT_PUBLIC_KEY_DER,
DEFAULT_PRIVATE_KEY_DER)
keyChain.sign(co, certificateName)
_data = co.wireEncode()
return _data.toRawStr()
示例2: handleDataInterests
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def handleDataInterests(self, prefix, interest, transport, prefixId):
# TODO: verification
# we match the components to the name, and any '_' components
# are discarded. Then we run a MongoDB query and append the
# object id to allow for excludes
chosenSchema = (s for s in self.schemaList
if s.dbPrefix.match(prefix)).next()
interestName = interest.getName()
responseName = Name(interestName)
nameFields = chosenSchema.matchNameToSchema(interestName)
self.log.info("Data requested with params:\n\t{}".format(nameFields))
allResults = []
segment = 0
try:
segmentComponent = interest.getName()[-4]
segment = segmentComponent.toSegment()
except RuntimeError:
pass
(startPos, results) = self._segmentResponseData(nameFields, segment)
for result in results:
dataId = result[u'_id']
self.log.debug("Found object {}".format(dataId))
allResults.append(result)
#responseName.append(str(dataId))
totalCount = results.count(False)
responseObject = {'count':totalCount, 'skip':startPos, 'results':allResults}
responseData = Data(responseName)
resultEncoded = BSON.encode(responseObject)
responseData.setContent(resultEncoded)
transport.send(responseData.wireEncode().buf())
示例3: publishData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [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)
示例4: __init__
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def __init__(self, prefix, maxCount=1):
self.keyChain = KeyChain()
self.prefix = Name(prefix)
self.isDone = False
# Initialize list for Data packet storage.
# We'll treat the indices as equivalent to the sequence
# number requested by Interests.
self.data = []
finalBlock = Name.Component.fromNumberWithMarker(maxCount - 1, 0x00)
hourMilliseconds = 3600 * 1000
# Pre-generate and sign all of Data we can serve.
# We can also set the FinalBlockID in each packet
# ahead of time because we know the entire sequence.
for i in range(maxCount):
dataName = Name(prefix).appendSegment(i)
data = Data(dataName)
data.setContent("Hello, " + dataName.toUri())
data.getMetaInfo().setFinalBlockID(finalBlock)
data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
self.data.append(data)
示例5: main
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [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")
示例6: test_copy_fields
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def test_copy_fields(self):
data = Data(self.freshData.getName())
data.setContent(self.freshData.getContent())
data.setMetaInfo(self.freshData.getMetaInfo())
self.credentials.signData(data)
freshDump = dumpData(data)
self.assertTrue(dataDumpsEqual(freshDump, initialDump), 'Freshly created data does not match original dump')
示例7: onPlayingCommand
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def onPlayingCommand(self, prefix, interest, transport, prefixId):
interestName = Name(interest.getName())
commandComponent = interest.getName().get(self.prefix.size())
if commandComponent == Name.Component("stop"):
pass
if commandComponent == Name.Component("play"):
pass
else:
songName = commandComponent.toEscapedString()
songList = []
songList = songName.split('%2C')
for i in songList:
fmusic = i + str("-music.mp3")
print "started getting music file", i
g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset, i)
g.oStream = open(fmusic,'wb')
g.start()
#self._getFiles.append(g)
d = Data(interest.getName())
d.setContent("start to play: " + songName + "\n")
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
示例8: onInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [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
示例9: onPlayingCommand
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def onPlayingCommand(self, prefix, interest, transport, prefixId):
print "receive interest"
interestName = Name(interest.getName())
commandComponent = interest.getName().get(self.prefix.size())
if commandComponent == Name.Component("stop"):
pass
if commandComponent == Name.Component("play"):
pass
else:
songName = commandComponent.toEscapedString()
print songName
songList = []
songList = songName.split('%2C')
print "songlist and its len",songList,len(songList)
for i in songList:
self.song = i
fmusic = i+str("-music.mp3")
self.ftxt = i + str("-os.txt")
self.ffreq = i + str("-freq.txt")
print "FMUSIC:",fmusic
self.thread = threading.Thread(target = self.mp.play_music, args = (fmusic,songList,self.q,))
self.thread.daemon = True
g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset)
#g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.lightFunction)
g.oStream = open(fmusic,'wb')
g.start()
d = Data(interest.getName())
d.setContent("start to play: " + songName + "\n")
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
示例10: generateData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def generateData(baseName):
'''
This appends the segment number to the data name
'''
# just make up some data and return it
ts = (time.time())
segmentId = 0 # compatible with repo-ng test: may change to test segmented data
versionComponent = baseName.get(-1) # should have a ts
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:
keychain.sign(d, certName)
else:
d.setSignature(fakeSignature)
if shouldCollectStats:
info = getInfoForVersion(versionComponent.toEscapedString())
if info is not None:
info['publish_time'] = ts
return d
示例11: onPublishInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def onPublishInterest(self, prefix, interest, transport, pxID):
'''
For publishing face
'''
# just make up some data and return it
interestName = interest.getName()
logger.info("Interest for " + interestName.toUri())
## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX!
dataName = Name(interestName)
ts = (time.time())
segmentId = 0
#try:
# segmentId = interestName.get(-1).toSegment()
#except:
#logger.debug("Could not find segment id!")
#dataName.appendSegment(segmentId)
versionStr = str(interestName.get(-2).getValue())
logger.debug('Publishing ' + versionStr + ' @ ' + str(ts))
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
d.getMetaInfo().setFreshnessPeriod(1000)
self.keychain.sign(d, self.certificateName)
encodedData = d.wireEncode()
stats.insertDataForVersion(versionStr, {'publish_time': time.time()})
transport.send(encodedData.toBuffer())
示例12: generateData
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [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
示例13: _onConfigurationReceived
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
# the interest we get here is signed by HMAC, let's verify it
self.tempPrefixId = prefixId # didn't get it from register because of the event loop
interestName = interest.getName()
replyData = Data(interestName)
if len(interestName) == len(prefix):
# this is a discovery request. Check the exclude to see if we should
# return our serial
serial = self.getSerial()
serialComponent = Name.Component(serial)
if not interest.getExclude().matches(serialComponent):
replyData.setContent(serial)
self.sendData(replyData, transport, False) # no point in signing
elif (self._hmacHandler.verifyInterest(interest)):
# we have a match! decode the network parameters
configComponent = interest.getName()[len(prefix)+1]
replyData.setContent('200')
self._hmacHandler.signData(replyData, keyName=self.prefix)
transport.send(replyData.wireEncode().buf())
environmentConfig = DeviceConfigurationMessage()
ProtobufTlv.decode(environmentConfig, configComponent.getValue())
networkPrefix = self._extractNameFromField(environmentConfig.configuration.networkPrefix)
controllerName = self._extractNameFromField(environmentConfig.configuration.controllerName)
controllerName = Name(networkPrefix).append(controllerName)
self._policyManager.setEnvironmentPrefix(networkPrefix)
self._policyManager.setTrustRootIdentity(controllerName)
self.deviceSuffix = self._extractNameFromField(environmentConfig.configuration.deviceSuffix)
self._configureIdentity = Name(networkPrefix).append(self.deviceSuffix)
self._sendCertificateRequest(self._configureIdentity)
示例14: onDeviceListRequest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def onDeviceListRequest(self, prefix, interest, transport, registeeredPrefix):
interestName = interest.getName()
username = interestName.get(4).getValue().toRawStr()
#TODO guest check
prefix = Name("/home/user/"+username)
userHash = self._deviceUserAccessManager.getUserHash(prefix)
userHMACKey = HMACKey(0,0,userHash,"userHMACKey")
dump("device dict : ",self._deviceDict)
if ( self._accessControlManager.verifyInterestWithHMACKey(interest,userHMACKey) ):
dump("Verified")
deviceProfileList = []
for prefixStr in self._deviceDict.keys():
tmp = self._deviceDict[prefixStr]['deviceProfile'].__dict__
dump("tmp :",tmp)
if (type(tmp["_prefix"]) != str):
tmp["_prefix"] = tmp["_prefix"].toUri()
deviceProfileList.append(tmp)
data = Data(interestName)
data.setContent(json.dumps(deviceProfileList))
self._accessControlManager.signDataWithHMACKey(data,userHMACKey)
self.sendData(data,transport,sign=False)
else:
dump("Not verified")
示例15: onDataInterest
# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import setContent [as 别名]
def onDataInterest(prefix, interest, transport, pxID):
'''
For publishing face
'''
# just make up some data and return it
interestName = interest.getName()
logger.info("Interest for " + interestName.toUri())
## CURRENTLY ASSUMES THERE'S A VERSION/SEGMENT SUFFIX!
dataName = Name(interestName.getPrefix(-1))
ts = (time.time())
segmentId = 0
try:
segmentId = interestName().get(-1).toSegment()
except:
logger.debug("Could not find segment id!")
dataName.appendSegment(segmentId)
versionStr = interestName.get(-2).getValue().toRawStr()
logger.debug('publishing ' + versionStr)
info = getInfoForVersion(versionStr)
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
keychain.sign(d, certName)
encodedData = d.wireEncode()
now = time.time()
if info is not None:
info['publish_time'] = now
transport.send(encodedData.toBuffer())