zookeeper python接口实例详解


Posted in Python onJanuary 18, 2018

本文主要讲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)

总结

以上就是本文关于zookeeper python接口实例详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
用Python操作字符串之rindex()方法的使用
May 19 Python
Python实现比较扑克牌大小程序代码示例
Dec 06 Python
详解pyqt5 动画在QThread线程中无法运行问题
May 05 Python
Python实现快速计算词频功能示例
Jun 25 Python
python3.7 sys模块的具体使用
Jul 22 Python
Python使用Tkinter实现滚动抽奖器效果
Jan 06 Python
Python语言异常处理测试过程解析
Jan 08 Python
win10安装python3.6的常见问题
Jul 01 Python
Python RabbitMQ实现简单的进程间通信示例
Jul 02 Python
Python __slots__的使用方法
Nov 15 Python
python Scrapy爬虫框架的使用
Jan 21 Python
详解Python中的GIL(全局解释器锁)详解及解决GIL的几种方案
Jan 29 Python
Python获取当前函数名称方法实例分享
Jan 18 #Python
Python AES加密实例解析
Jan 18 #Python
快速了解python leveldb
Jan 18 #Python
Python实现动态图解析、合成与倒放
Jan 18 #Python
Python基于matplotlib实现绘制三维图形功能示例
Jan 18 #Python
Python实现在tkinter中使用matplotlib绘制图形的方法示例
Jan 18 #Python
python中requests和https使用简单示例
Jan 18 #Python
You might like
Thinkphp中volist标签mod控制一定记录的换行BUG解决方法
2014/11/04 PHP
php文件上传、下载和删除示例
2020/08/28 PHP
Yii统计不同类型邮箱数量的方法
2016/10/18 PHP
js自动下载文件到本地的实现代码
2013/04/28 Javascript
Javascript 多物体运动的实现
2014/12/24 Javascript
AngularJS  双向数据绑定详解简单实例
2016/10/20 Javascript
JS图片延迟加载插件LazyImgv1.0用法分析【附demo源码下载】
2017/09/04 Javascript
vue watch监听对象及对应值的变化详解
2018/02/24 Javascript
vue3.0 CLI - 2.3 - 组件 home.vue 中学习指令和绑定
2018/09/14 Javascript
微信小程序中遇到的iOS兼容性问题小结
2018/11/14 Javascript
[00:38]TI珍贵瞬间系列(二):笑
2020/08/26 DOTA
Python中title()方法的使用简介
2015/05/20 Python
Python批量重命名同一文件夹下文件的方法
2015/05/25 Python
Python操作Excel之xlsx文件
2017/03/24 Python
python实现石头剪刀布小游戏
2021/01/20 Python
python 定时器,轮询定时器的实例
2019/02/20 Python
python gensim使用word2vec词向量处理中文语料的方法
2019/07/05 Python
Python基于百度AI实现OCR文字识别
2020/04/02 Python
PyCharm+Pipenv虚拟环境开发和依赖管理的教程详解
2020/04/16 Python
Python matplotlib 绘制双Y轴曲线图的示例代码
2020/06/12 Python
美国网上眼镜商城:Zenni Optical
2016/11/20 全球购物
神路信息Java面试题目
2013/03/31 面试题
制衣厂各岗位职责
2013/12/02 职场文书
第一批党的群众路线教育实践活动工作总结
2014/03/03 职场文书
大学班级学风建设方案
2014/05/01 职场文书
节能宣传周活动总结
2014/05/08 职场文书
励志演讲稿600字
2014/08/21 职场文书
高中美术教师事迹材料
2014/08/22 职场文书
影视广告专业求职信
2014/09/02 职场文书
法学专业毕业实习自我鉴定2014
2014/09/27 职场文书
查摆剖析材料范文
2014/09/30 职场文书
作文评语怎么写
2014/12/25 职场文书
会计求职自荐信范文
2015/03/04 职场文书
《包身工》教学反思
2016/02/23 职场文书
如何自己动手写SQL执行引擎
2021/06/02 MySQL
java中重写父类方法加不加@Override详解
2021/06/21 Java/Android