python kazoo模块的使用

kazoo是zookeeper的python模块,使用python编写的。使用python写运维平台的就可以用上

1、安装
安装简单,不需要其他依赖

pip install kazoo

2、使用

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
参考:http://kazoo.readthedocs.io/en/latest/basic_usage.html#creating-nodes
'''

from kazoo.client import KazooClient

# Create a client and start it
zk = KazooClient(hosts='10.14.86.178:2181')
zk.start()

# Now you can do the regular zookepper API calls
# Ensure some paths are created required by your application
# zk.ensure_path("/app/someservice")


#watchers
# @zk.ChildrenWatch('/mysql/host')
# def mysql_watcher(children):
#     print('/mysql/host changed :%s'%children)


#获取指定节点的值
# print(zk.get('/mysql/host',watch=mysql_watcher2))
# print(zk.get('/mysql/port',watch=None))
# print(zk.get('/mysql/user',watch=None))
# print(zk.get('/mysql/pwd',watch=None))

'''
Reading Data
Methods:
    exists()
    get()           获取key对应的value值
    get_children()  获取节点下的key信息
'''
# Determine if a node exists
# if zk.exists("/redis/group1"):
#     # Do something
#     print(zk.get_children('/redis/group1'))
#     print(zk.get('/redis/group1/host'))

'''
Creating Nodes
Methods:
    ensure_path()   插入节点
    create()        创建节点key,value
'''
# zk.ensure_path('/mysql/test')
# zk.create('/mysql/test/node',b'node value')

'''
Updating Data
Methods:
    set()
'''
# zk.set('/mysql/test/node',b'value')
# print(zk.get('/mysql/test/node'))

'''
Deleting Nodes
Methods:
    delete()
'''
zk.delete('/mysql/test',recursive=True)


# In the end, stop it
zk.stop()



2.1、连接状态 zk.state

有三个值,LOST、CONNECTED、SUSPENDED
QQ图片20150408141901

2.2、zk.connected
已连接上返回True
没有连接上返回False

2.3、zk.get(path, watch=None)
获取指定节点的值,节点不存在触发NoNodeError异常

2.4、zk.get_children(path, watch=None)
获取指定节点子节点信息
QQ图片20150408141922

3、web展示结果
zookeeper7

4、后台逻辑

def base(basedir, id, pid):
    '''
    id:当前节点的id,ID的组成是 深度 + 兄弟节点序号 + 父节点ID
    pid: 父节点id
    name: 节点名称
    children: 子节点个数
    deep: 深度
    url: 节点的路径
    '''
    deep = ''
    try:
        if not zk.connected:
            zk.start()
        item = {}
        if basedir == '/':
            children = ['redis', 'game', 'uc']
        else:
            children = zk.get_children(basedir)
        cut = basedir.split('/')
        deep = len(cut) - 1
        name = cut[deep]
        if len(children) == 0:
            childrenlen = 0
        else:
            childrenlen = len(children)
        item = {'id': id, 'pid': pid, 'name': name, 'children': childrenlen, 'deep': deep, 'url': basedir}
        datas.append(item)
        for i in xrange(len(children)):
            path = os.path.join(basedir, children[i])
            cut = path.split('/')
            n_id = str(len(cut) - 1) + str(i) + str(id)
            base(path, n_id, id)
    except Exception, e:
        data = str(e)
    return datas


def get_children(req):
    status = 0
    message = ''
    data = []
    global datas
    datas = []
    basedir = '/'
    try:
        data = base(basedir, '10', '0')
    except Exception, e:
        status = -1
        message = str(e)
    zk.stop()
    result = stringify(status, message, data)
    return HttpResponse(result)

参考资料:
https://kazoo.readthedocs.org/en/latest/install.html

http://sapser.github.io/python/zookeeper/2014/07/24/zookeeper-kazoo/

转自:

http://zgssheng.cn/2015/04/kazoo-zookeeper-python%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8/

Python可以使用`kazoo`库来与ZooKeeper进行交互。Kazoo是一个Python库,提供了与ZooKeeper的连接和操作的API。下面是使用PythonKazoo库连接和使用ZooKeeper的基本步骤: 1. 安装Kazoo库:可以使用pip命令来安装Kazoo库,运行以下命令: ``` pip install kazoo ``` 2. 连接到ZooKeeper:使用Kazoo库的`KazooClient`类来创建一个ZooKeeper客户端对象,并连接到ZooKeeper服务器。示例代码如下: ```python from kazoo.client import KazooClient # 创建ZooKeeper客户端对象 zk = KazooClient(hosts='127.0.0.1:2181') # 连接到ZooKeeper服务器 zk.start() ``` 3. 创建节点:使用`create`方法来在ZooKeeper中创建节点。示例代码如下: ```python # 创建一个节点 zk.create('/my_node', b'my_data') ``` 4. 获取节点数据:使用`get`方法来获取节点的数据。示例代码如下: ```python # 获取节点数据 data, stat = zk.get('/my_node') print(data.decode()) ``` 5. 监听节点变化:使用`DataWatch`类来监听节点的数据变化。示例代码如下: ```python from kazoo.recipe.watchers import DataWatch # 监听节点数据变化 @DataWatch('/my_node') def watch_node(data, stat): print(f"Node data changed: {data.decode()}") # 等待节点数据变化 while True: pass ``` 这些是使用PythonKazoo库与ZooKeeper进行交互的基本步骤。你可以根据具体需求使用Kazoo库提供的其他方法来操作ZooKeeper。如果你有任何进一步的问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值