本文整理汇总了Python中kademlia.network.Server.set方法的典型用法代码示例。如果您正苦于以下问题:Python Server.set方法的具体用法?Python Server.set怎么用?Python Server.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kademlia.network.Server
的用法示例。
在下文中一共展示了Server.set方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DHTResolver
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class DHTResolver(object):
def __init__(self, config, bootstrapNeighbors):
self.config = config
self.log = Logger(system=self)
if os.path.isfile(config['dht.state.cache']):
self.kserver = Server.loadState(config['dht.state.cache'])
else:
self.kserver = Server()
self.kserver.bootstrap(bootstrapNeighbors)
self.kserver.saveStateRegularly(config['dht.state.cache'], 60)
def getProtocol(self):
return self.kserver.protocol
def getPublicKey(self, keyId):
"""
Get the public key from the network, and return only if the key is
the one that matches the keyId based on hash.
"""
def verify(key):
if key is not None and PublicKey(key).getKeyId() == keyId:
return key
return None
self.log.debug("Getting key text for key id %s" % keyId)
return self.kserver.get(keyId).addCallback(verify)
def resolve(self, keyId):
def parse(locations):
self.log.debug("Locations for %s: %s" % (keyId, locations))
results = []
if locations is None or locations == "":
return results
for location in locations.split(','):
host, port = location.split(':')
results.append((host, int(port)))
return results
d = self.kserver.get("%s-location" % keyId)
return d.addCallback(parse)
def announceLocation(self, myKeyId, myPublicKey):
def announce(ips):
ips = self.localAddresses() + ips
ipports = map(lambda ip: "%s:%i" % (ip, self.config['s2s.port']), ips)
return self.kserver.set("%s-location" % myKeyId, ",".join(ipports))
d = self.kserver.set(myKeyId, str(myPublicKey))
d.addCallback(lambda _: self.kserver.inetVisibleIP())
return d.addCallback(announce)
def localAddresses(self):
result = []
for iface in netifaces.interfaces():
addys = netifaces.ifaddresses(iface).get(netifaces.AF_INET)
result += [ addy['addr'] for addy in (addys or []) if addy['addr'] != '127.0.0.1' ]
return result
示例2: KademliaUser
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class KademliaUser(Runnable):
"""Allows the KademliaUser to be run in its own thread."""
def __init__(self, name="KademliaUser%d"%random.randint(1, 1000),
port=emu_config.kademlia_default_port, peerlist=None):
super(KademliaUser, self).__init__(name=name)
self.kademliaServer = Server()
self.port = port
self.peerlist = peerlist if peerlist is not None else []
def start(self):
"""Implements start() from the superclass."""
self._startKademlia()
try:
IOLoop.current().start()
except socket.error as ex:
logging.warning("Could not start the KademliaUser: %s"%ex)
def _startKademlia(self):
possible_interfaces = [iface for iface in netifaces.interfaces() if iface_searchterm in iface
and netifaces.ifaddresses(iface).has_key(netifaces.AF_INET)]
if len(possible_interfaces) == 0:
logging.error("No suitable interfaces found, tried the following: %s"%netifaces.interfaces())
logging.debug("Interfaces: %s"%netifaces.ifaddresses(possible_interfaces[0]))
ipAddr = netifaces.ifaddresses(possible_interfaces[0])[netifaces.AF_INET][0]["addr"]
logging.debug("Node %s starts with %s on %s"%(self.name, self.peerlist, ipAddr))
self.kademliaServer.listen(self.port, interface=ipAddr)
serverDeferred = self.kademliaServer.bootstrap([(peer, emu_config.kademlia_default_port) for peer in self.peerlist])
serverDeferred.addCallback(self.executeBot)
serverDeferred.addErrback(self.errback)
def executeBot(self, peersfound=None):
"""Method that is called regularly and checks for new commands"""
self.kademliaServer.get(generateRandomString(length=2)).addCallbacks(self.ignoreInput, self.errback)
self.kademliaServer.set(generateRandomString(length=2), generateRandomString()).addCallbacks(self.ignoreInput,
self.errback)
reactor.callLater(emu_config.botcommand_timeout, self.executeBot)
def ignoreInput(self, *args, **kwargs):
"""Gets whatever is the result of the Kademlia GET request and ignores it"""
pass
def errback(self, failure, *args, **kwargs):
"""Given to defereds to report errors. Ignores those errors."""
logging.debug(
"Kademlia Error (for the legitimate user, so non-existing keys are not a problem) in %s: %s"%(self.name, failure))
pass
示例3: __init__
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class BitHaikuDHT:
log = logging.getLogger(__name__)
def __init__(self, configuration):
self.configuration = configuration
self.server = Server()
self.server.listen(configuration.ports.dht)
self.server.bootstrap([(configuration.local_address, configuration.ports.dht)])
def add(self, ip):
self.log.error("Bootstrapping " + ip)
self.server.bootstrap([(ip, self.configuration.ports.dht)])
def find_owner(self, data):
key = value = hashlib.sha256(data).hexdigest()
self.server.set(key, value)
digest = kademlia.utils.digest(hash)
node = Node(digest)
nearest = self.server.protocol.router.findNeighbors(node)
return nearest[0].ip
示例4: DHTResolver
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class DHTResolver(object):
def __init__(self, config, bootstrapNeighbors):
if os.path.isfile(config['dht.state.cache']):
self.kserver = Server.loadState(config['dht.state.cache'])
else:
self.kserver = Server()
self.kserver.bootstrap(bootstrapNeighbors)
self.kserver.saveStateRegularly(config['dht.state.cache'], 60)
def getProtocol(self):
return self.kserver.protocol
def resolve(self, keyId):
return self.kserver.get(keyId)
def announceLocation(self, myKeyId):
def announce(ips):
if len(ips) == 0:
return defer.succeed(False)
return self.kserver.set(myKeyId, ips[0])
d = self.kserver.inetVisibleIP()
return d.addCallback(announce)
示例5: NetworkInterface
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class NetworkInterface (object):
# Create a NetworkInterface object to accomplish all network related tasks
def __init__(self, appDeployer, uuid):
self._connected = False
self._app_deployer = appDeployer
# optional...
self._number_of_nodes = 0
self._list_of_nodes =[]
# logging capabilities
self._log = Logger(system=self)
# HERE--> Implementation specific node instanciation
from kademlia.network import Server
self._node = Server()
self._node.log.level = 4
# END OF SECTION
def bootStrapDone(self, server):
#contacts = self._node.inetVisibleIP()
print "BOOOOTTTT STAPPP IT"
def retrieveContacts(self):
"""
NEED TO FIND A WAY TO RETRIEVE THE LIST OF NEIGHBORS !!!
"""
# !!! DOES EXACTLY THE SAME AS bootstrappableNeighbors !!!
for bucket in self._node.protocol.router.buckets:
print bucket.getNodes()
# !!! bootstrappableNeighbors returns only the list of neighbors that you provided as !!!
# !!! a bootstrap list, that are also online !!!
neighbors = self._node.bootstrappableNeighbors()
print neighbors
return neighbors
def connect(self,fromPort,toPort,ip='127.0.0.1'):
self._log.debug('Connecting...')
#print "in connect ... "
#print "now listening on port: ",fromPort
self._node.listen(fromPort)
return self._node.bootstrap([(ip,toPort)]).addCallback(self.bootStrapDone)
# This function is used to set a value in the DHT
def setDone(self,result):
print result
print "set is done"
deferred = Deferred()
return deferred
def set(self, key, value):
def _processKey(result, key, values):
print result, key, values
deferred = Deferred()
# upon recovering the value of the key
if result == None:
deferred = self._node.set(key, values)
return deferred
#.addCallback(self.setDone)
else:
for value in values:
if value not in result:
# append + publish
result.append(value)
else:
self._log.info("Value is already in the corresponding key.")
deferred = self._node.set(key, result)
return deferred
# Only application deployers are allowed to write to the DHT.
if self._app_deployer != False:
deferred = Deferred()
# Two possible keys are allowed to be written to, the template key and their respective application key
if ('template' == key or self._uuid == key) and key != None:
# HERE --> Implementation Specific Code
print " ::: ", self, " ::: ", key, " ::: ", value, " <----------------------------"
# if writing to the template, retrieve the value first then append to it if necessary
if key == 'template':
deferred = self._node.get(key)
deferred.addCallback(_processKey, key, value)
return deferred
#self._node.set(key, value).addCallback(self.setDone)
# END OF SECTION
# Not Allowed to write to the DHT.
else:
self._log.info("Only application deployers are allowed to write values into the DHT!")
def done(self,result):
print "self: ", self
print "Key result:", result
#.........这里部分代码省略.........
示例6: len
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
import logging
import asyncio
import sys
from kademlia.network import Server
if len(sys.argv) != 5:
print("Usage: python set.py <bootstrap node> <bootstrap port> <key> <value>")
sys.exit(1)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
log = logging.getLogger('kademlia')
log.addHandler(handler)
log.setLevel(logging.DEBUG)
loop = asyncio.get_event_loop()
loop.set_debug(True)
server = Server()
loop.run_until_complete(server.listen(8469))
bootstrap_node = (sys.argv[1], int(sys.argv[2]))
loop.run_until_complete(server.bootstrap([bootstrap_node]))
loop.run_until_complete(server.set(sys.argv[3], sys.argv[4]))
server.stop()
loop.close()
示例7: NetworkInterface
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import set [as 别名]
class NetworkInterface (object):
# Create a NetworkInterface object to accomplish all network related tasks
def __init__(self, appDeployer=False):
self._connected = False
self._app_deployer = appDeployer
# optional...
self._number_of_nodes = 0
self._list_of_nodes =[]
# logging capabilities
self._log = Logger(system=self)
# HERE--> Implementation specific node instanciation
from kademlia.network import Server
self._node = Server()
self._node.log.level = 4
# END OF SECTION
def bootStrapDone(self, server):
#contacts = self._node.inetVisibleIP()
print "BOOOOTTTT STAPPP IT"
def retrieveContacts(self):
"""
NEED TO FIND A WAY TO RETRIEVE THE LIST OF NEIGHBORS !!!
"""
# !!! DOES EXACTLY THE SAME AS bootstrappableNeighbors !!!
for bucket in self._node.protocol.router.buckets:
print bucket.getNodes()
# !!! bootstrappableNeighbors returns only the list of neighbors that you provided as !!!
# !!! a bootstrap list, that are also online !!!
neighbors = self._node.bootstrappableNeighbors()
print neighbors
return neighbors
def connect(self,fromPort,toPort,ip='127.0.0.1'):
self._log.debug('Connecting...')
#print "in connect ... "
#print "now listening on port: ",fromPort
self._node.listen(fromPort)
return self._node.bootstrap([(ip,toPort)]).addCallback(self.bootStrapDone)
# This function is used to set a value in the DHT
def setDone(self,result):
print result
print "set is done"
def set(self,result, key, value):
# HERE --> Implementation Specific Code
print result, " ::: ", self, " ::: ", key, " ::: ", value, " <----------------------------"
self._node.set(key, value).addCallback(self.setDone)
# END OF SECTION
def done(self,result):
print "self: ", self
print "Key result:", result
def get(self,result, key):
# HERE --> Implementation Specific Code
print result, " ::: ", self, " ::: ", key, " <----------------------------"
self._node.get(key).addCallback(self.done)