zookeeper python接口实例详解
作者:swpihchj 发布时间:2023-03-11 01:34:48
标签:zookeeper,python,接口
本文主要讲python支持zookeeper的接口库安装和使用。zk的python接口库有zkpython,还有kazoo,下面是zkpython,是基于zk的C库的python接口。
zkpython安装
前提是zookeeper安装包已经在/usr/local/zookeeper下
cd /usr/local/zookeeper/src/c
./configure
make
make install
wget --no-check-certificate http://pypi.python.org/packages/source/z/zkpython/zkpython-0.4.tar.gz
tar -zxvf zkpython-0.4.tar.gz
cd zkpython-0.4
sudo python setup.py install
zkpython应用
下面是网上一个zkpython的类,用的时候只要import进去就行
vim zkclient.py
#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-
import zookeeper, time, threading
from collections import namedtuple
DEFAULT_TIMEOUT = 30000
VERBOSE = True
ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
# Mapping of connection state values to human strings.
STATE_NAME_MAPPING = {
zookeeper.ASSOCIATING_STATE: "associating",
zookeeper.AUTH_FAILED_STATE: "auth-failed",
zookeeper.CONNECTED_STATE: "connected",
zookeeper.CONNECTING_STATE: "connecting",
zookeeper.EXPIRED_SESSION_STATE: "expired",
}
# Mapping of event type to human string.
TYPE_NAME_MAPPING = {
zookeeper.NOTWATCHING_EVENT: "not-watching",
zookeeper.SESSION_EVENT: "session",
zookeeper.CREATED_EVENT: "created",
zookeeper.DELETED_EVENT: "deleted",
zookeeper.CHANGED_EVENT: "changed",
zookeeper.CHILD_EVENT: "child",
}
class ZKClientError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ClientEvent(namedtuple("ClientEvent", 'type, connection_state, path')):
"""
A client event is returned when a watch deferred fires. It denotes
some event on the zookeeper client that the watch was requested on.
"""
@property
def type_name(self):
return TYPE_NAME_MAPPING[self.type]
@property
def state_name(self):
return STATE_NAME_MAPPING[self.connection_state]
def __repr__(self):
return "<ClientEvent %s at %r state: %s>" % (
self.type_name, self.path, self.state_name)
def watchmethod(func):
def decorated(handle, atype, state, path):
event = ClientEvent(atype, state, path)
return func(event)
return decorated
class ZKClient(object):
def __init__(self, servers, timeout=DEFAULT_TIMEOUT):
self.timeout = timeout
self.connected = False
self.conn_cv = threading.Condition( )
self.handle = -1
self.conn_cv.acquire()
if VERBOSE: print("Connecting to %s" % (servers))
start = time.time()
self.handle = zookeeper.init(servers, self.connection_watcher, timeout)
self.conn_cv.wait(timeout/1000)
self.conn_cv.release()
if not self.connected:
raise ZKClientError("Unable to connect to %s" % (servers))
if VERBOSE:
print("Connected in %d ms, handle is %d"
% (int((time.time() - start) * 1000), self.handle))
def connection_watcher(self, h, type, state, path):
self.handle = h
self.conn_cv.acquire()
self.connected = True
self.conn_cv.notifyAll()
self.conn_cv.release()
def close(self):
return zookeeper.close(self.handle)
def create(self, path, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):
start = time.time()
result = zookeeper.create(self.handle, path, data, acl, flags)
if VERBOSE:
print("Node %s created in %d ms"
% (path, int((time.time() - start) * 1000)))
return result
def delete(self, path, version=-1):
start = time.time()
result = zookeeper.delete(self.handle, path, version)
if VERBOSE:
print("Node %s deleted in %d ms"
% (path, int((time.time() - start) * 1000)))
return result
def get(self, path, watcher=None):
return zookeeper.get(self.handle, path, watcher)
def exists(self, path, watcher=None):
return zookeeper.exists(self.handle, path, watcher)
def set(self, path, data="", version=-1):
return zookeeper.set(self.handle, path, data, version)
def set2(self, path, data="", version=-1):
return zookeeper.set2(self.handle, path, data, version)
def get_children(self, path, watcher=None):
return zookeeper.get_children(self.handle, path, watcher)
def async(self, path = "/"):
return zookeeper.async(self.handle, path)
def acreate(self, path, callback, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):
result = zookeeper.acreate(self.handle, path, data, acl, flags, callback)
return result
def adelete(self, path, callback, version=-1):
return zookeeper.adelete(self.handle, path, version, callback)
def aget(self, path, callback, watcher=None):
return zookeeper.aget(self.handle, path, watcher, callback)
def aexists(self, path, callback, watcher=None):
return zookeeper.aexists(self.handle, path, watcher, callback)
def aset(self, path, callback, data="", version=-1):
return zookeeper.aset(self.handle, path, data, version, callback)
watch_count = 0
"""Callable watcher that counts the number of notifications"""
class CountingWatcher(object):
def __init__(self):
self.count = 0
global watch_count
self.id = watch_count
watch_count += 1
def waitForExpected(self, count, maxwait):
"""Wait up to maxwait for the specified count,
return the count whether or not maxwait reached.
Arguments:
- `count`: expected count
- `maxwait`: max milliseconds to wait
"""
waited = 0
while (waited < maxwait):
if self.count >= count:
return self.count
time.sleep(1.0);
waited += 1000
return self.count
def __call__(self, handle, typ, state, path):
self.count += 1
if VERBOSE:
print("handle %d got watch for %s in watcher %d, count %d" %
(handle, path, self.id, self.count))
"""Callable watcher that counts the number of notifications
and verifies that the paths are sequential"""
class SequentialCountingWatcher(CountingWatcher):
def __init__(self, child_path):
CountingWatcher.__init__(self)
self.child_path = child_path
def __call__(self, handle, typ, state, path):
if not self.child_path(self.count) == path:
raise ZKClientError("handle %d invalid path order %s" % (handle, path))
CountingWatcher.__call__(self, handle, typ, state, path)
class Callback(object):
def __init__(self):
self.cv = threading.Condition()
self.callback_flag = False
self.rc = -1
def callback(self, handle, rc, handler):
self.cv.acquire()
self.callback_flag = True
self.handle = handle
self.rc = rc
handler()
self.cv.notify()
self.cv.release()
def waitForSuccess(self):
while not self.callback_flag:
self.cv.wait()
self.cv.release()
if not self.callback_flag == True:
raise ZKClientError("asynchronous operation timed out on handle %d" %
(self.handle))
if not self.rc == zookeeper.OK:
raise ZKClientError(
"asynchronous operation failed on handle %d with rc %d" %
(self.handle, self.rc))
class GetCallback(Callback):
def __init__(self):
Callback.__init__(self)
def __call__(self, handle, rc, value, stat):
def handler():
self.value = value
self.stat = stat
self.callback(handle, rc, handler)
class SetCallback(Callback):
def __init__(self):
Callback.__init__(self)
def __call__(self, handle, rc, stat):
def handler():
self.stat = stat
self.callback(handle, rc, handler)
class ExistsCallback(SetCallback):
pass
class CreateCallback(Callback):
def __init__(self):
Callback.__init__(self)
def __call__(self, handle, rc, path):
def handler():
self.path = path
self.callback(handle, rc, handler)
class DeleteCallback(Callback):
def __init__(self):
Callback.__init__(self)
def __call__(self, handle, rc):
def handler():
pass
self.callback(handle, rc, handler)
来源:http://blog.csdn.net/swpihchj/article/details/24603641
0
投稿
猜你喜欢
- 最近要做一个图像生成的课题,在网上找了一个混合的数据集。这个数据集中一共有360个文件夹,然后文件夹中有6-9张不等的照片,我的目标就是编写
- 通过引用serial模块包,来操作串口。1、查看串口名称在Linux和Windows中,串口的名字规则不太一样。需要事先查看。Linux下的
- 目标文件夹内有多份 Word 文件 ——【xxx涨薪通告.docx】,我们需要在这些文档的末尾处添加
- 本文适用范围:全面阐述MySQL数据库的各种操作,分虚拟主机和服务器两种情况。虚拟主机1、通过PHPMyAdmin的导入导出功能,这个软件一
- 本文通过Python3+PyQt5实现自定义部件–Counters自定 窗口部件。这个窗口是3*3的网格。本文有两个例子如下: /home/
- 前言当今,随着计算机技术的发展,摄像头已经成为了人们生活中不可或缺的一部分。而Python作为一种流行的编程语言,也可以轻松地控制和操作摄像
- sys;//系统管理员,拥有最高权限 system;//本地管理员,次高权限 scott;//普通用户,密码默认为tiger,默认未解锁 s
- 数据标准化是机器学习、数据挖掘中常用的一种方法。包括我自己在做深度学习方面的研究时,数据标准化是最基本的一个步骤。数据标准化主要是应对特征向
- 前言猪年除夕之夜在亲人群抢红包心血来潮,想用python做比较好玩的新年祝福给亲人们乐呵乐呵。奈何初学Python,底子比较薄,通过查阅相关
- 如下所示:import http.client, urllib.parseimport http.client, urllib.parsei
- SQLite Delete详解SQLite 的 DELETE 查询用于删除表中已有的记录。可以使用带有 WHERE 子句的 DELETE 查
- JWT介绍Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准.该token被设计为
- memcache 的工作就是在专门的机器的内存里维护一张巨大的hash表,来存储经常被读写的一些数组与文件,从而极大的提高网站的运行效率,减
- 环境准备Python3.6pip install Django==2.0.1pip install celery==4.1.0pip ins
- Python是一种非常富有表现力的语言。它为我们提供了一个庞大的标准库和许多内置模块,帮助我们快速完成工作。然而,许多人可能会迷失在它提供的
- 前言Golang中当程序发生致命异常时(比如数组下标越界,注意这里的异常并不是error),Golang程序会panic(运行时恐慌)。当程
- 想要根据django中的模型和配置生成SQL语句,需要先进行一定的设置:首先需要在你的app文件夹中进入setting.py文件,里面有一个
- 在写一个多线程类的时候调用报错 RuntimeError: thread.__init__() not calledclass Notify
- 由于连续的字符(字母、符号、数字)在默认情况下是不换行的,可能会破坏整个界面布局。那如何解决这个问题呢?在 IE 和 Safari 1.3+
- 简介Python中布尔值(Booleans)表示以下两个值之一:True或False。布尔值在编程中,通常需要知道表达式是 True 还是