How to watch child child nodes in Python using kazoo?

I recently started working with Python for Zookeeper. I use the library kazoofor Zookeeper.

I have a very simple example of using kazoo for Zookeeper. I have a root node, which is - /root. Now I need to monitor the root of the node /root, and if the new node that is being added to the root node /rootis this /root/testing, then I will only store the clock on the /root/testingnode. I do not want to keep track of any nodes other than testingnode. And then if any new children are added to the /root/testingnode, I will also look at them.

Say a child below this is added -

`/root/testing/test1`

Then I will look at test1node.

Can this be done with Kazoo in Zookeeper? I can only keep track of one Zookeeper node ( /root) using the code below:

#!/usr/bin/python
import time

from kazoo.client import KazooClient

zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()

########################################
@zk.ChildrenWatch("/root/testing")
def watch_children(children):
   print(children)

########################################

while True:
    time.sleep(5)

Can someone help me with this in creating a few hours for a child node?

+4
source share
2 answers

Try something like this.

import time
from kazoo.client import KazooClient

zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()

children = zk.get_children("/root/",)
if "/testing" in children:
    children_testing = zk.get_children("/root/testing/")
        if children_testing != []: 
            @zk.ChildrenWatch("/root/testing")
            def watch_children(children):
                print(children)
        else:
            @zk.ChildrenWatch("/root/")
            def watch_children(children):
                print(children)
while True:
    time.sleep(5)
+1
source

If you are trying to monitor multiple nodes, rather than one, you can use several threads (basically it runs different code at the same time on different "threads"). Python has a streaming module for simultaneous actions, which may be exactly what you want. The following is sample code with streams enabled.

import threading

def watch_node(node):
    #implement your node watching script here

def watch_in_background(node):
    watcher = threading.Thread(target=watch_node,args=(node))   #initializes a thread that can run the watch_node function in the background, passing the node argument to it
    watcher.start()                                             #tells the thread to start running
    return watcher                                              #returns the thread object just in case you want to use it for something

watch_in_background(<node>)                                     #so this code will now watch the node in the background, allowing you to do other things, like watch multiple nodes
0
source

All Articles