Values With Subkeys
Values with subkeys
The Mesh DHT also supports a special value type that is itself a dictionary. When nodes store such a value, they add subkeys to the dictionary instead of overwriting it.
Consider an example where three DHT nodes want to find out who is going to attend the party:
alice_dht = DHT(initial_peers=dht.get_visible_maddrs(), start=True)
bob_dht = DHT(initial_peers=dht2.get_visible_maddrs(), start=True)
carol_dht = DHT(initial_peers=alice_dht.get_visible_maddrs(), start=True)
# first, each peer stores a subkey for the same key
alice_dht.store('party', subkey='alice', value='yes', expiration_time=get_dht_time() + 600)
bob_dht.store('party', subkey='bob', value='yes', expiration_time=get_dht_time() + 600)
carol_dht.store('party', subkey='carol', value='no', expiration_time=get_dht_time() + 600)
# then, any peer can get the full list of attendees
attendees, expiration = alice_dht.get('party', latest=True)
print(attendees)
# {'alice': ValueWithExpiration(value='yes', expiration_time=1625504352.2668974),
# 'bob': ValueWithExpiration(value='yes', expiration_time=1625504352.2884178),
# 'carol': ValueWithExpiration(value='no', expiration_time=1625504352.3046832)}
When running over the Internet, some dht.get/store
requests may run for hundreds of milliseconds and even seconds. To minimize the wait time, you can call these requests asynchronously via dht.store/get/run_coroutine(..., return_future=True)
. This will run the corresponding command in the background and return a Future-like object that can be awaited. Please also note that the returned future is compatible with asyncio (i.e., can be awaited inside the event loop).
For more details on DHT store/get and expiration time, please refer to the documentation for DHT and DHTNode.
Last updated