From a6e50acd844e29bf73592584a6d857b7e8dc5a8a Mon Sep 17 00:00:00 2001 From: Vicente Dragicevic Date: Mon, 16 Oct 2017 18:17:35 -0300 Subject: [PATCH] @python3.5 - Fix saving/loading state (#37) * Fix await self.find() in crawler * Fix state loading/saving * Fix saveStateRegularly (it was using a Twisted function) * Use loop.call_later for saveStateRegularly and cancel task on server.stop() * Remove innecessary function * Add missing initialization of save_state_loop, and changed the checks for Noneness --- kademlia/network.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/kademlia/network.py b/kademlia/network.py index ad9a47e..0cdb023 100644 --- a/kademlia/network.py +++ b/kademlia/network.py @@ -40,14 +40,18 @@ class Server(object): self.transport = None self.protocol = None self.refresh_loop = None + self.save_state_loop = None def stop(self): - if self.refresh_loop is not None: - self.refresh_loop.cancel() - if self.transport is not None: self.transport.close() + if self.refresh_loop: + self.refresh_loop.cancel() + + if self.save_state_loop: + self.save_state_loop.cancel() + def listen(self, port, interface='0.0.0.0'): """ Start listening on the given port. @@ -193,7 +197,7 @@ class Server(object): if len(data['neighbors']) == 0: self.log.warning("No known neighbors, so not writing to cache.") return - with open(fname, 'w') as f: + with open(fname, 'wb') as f: pickle.dump(data, f) @classmethod @@ -202,7 +206,7 @@ class Server(object): Load the state of this node (the alpha/ksize/id/immediate neighbors) from a cache file with the given fname. """ - with open(fname, 'r') as f: + with open(fname, 'rb') as f: data = pickle.load(f) s = Server(data['ksize'], data['alpha'], data['id']) if len(data['neighbors']) > 0: @@ -216,9 +220,9 @@ class Server(object): Args: fname: File name to save retularly to - frequencey: Frequency in seconds that the state should be saved. + frequency: Frequency in seconds that the state should be saved. By default, 10 minutes. """ - loop = LoopingCall(self.saveState, fname) - loop.start(frequency) - return loop + self.saveState(fname) + loop = asyncio.get_event_loop() + self.save_state_loop = loop.call_later(frequency, self.saveStateRegularly, fname, frequency)