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 相关文章推荐
wxpython中利用线程防止假死的实现方法
Aug 11 Python
编写Python脚本批量下载DesktopNexus壁纸的教程
May 06 Python
Python处理字符串之isspace()方法的使用
May 19 Python
Python文本特征抽取与向量化算法学习
Dec 22 Python
Python编写合并字典并实现敏感目录的小脚本
Feb 26 Python
Python基础之条件控制操作示例【if语句】
Mar 23 Python
Python matplotlib学习笔记之坐标轴范围
Jun 28 Python
Python @property装饰器原理解析
Jan 22 Python
python GUI库图形界面开发之PyQt5动态加载QSS样式文件
Feb 25 Python
基于Python快速处理PDF表格数据
Jun 03 Python
python属于解释语言吗
Jun 11 Python
Django QuerySet查询集原理及代码实例
Jun 13 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
DC动漫人物排行
2020/03/03 欧美动漫
使用 php4 加速 web 传输
2006/10/09 PHP
php使用pdo连接报错Connection failed SQLSTATE的解决方法
2014/12/15 PHP
PHP生成可点击刷新的验证码简单示例
2016/05/13 PHP
Yii框架表单提交验证功能分析
2017/01/07 PHP
PHP后端银联支付及退款实例代码
2017/06/23 PHP
yii2局部关闭(开启)csrf的验证的实例代码
2017/07/10 PHP
PHP实现的Redis多库选择功能单例类
2017/07/27 PHP
(推荐一个超好的JS函数库)S.Sams Lifexperience ScriptClassLib
2007/04/29 Javascript
如何让div span等元素能响应键盘事件操作指南
2012/11/13 Javascript
一些常用弹出窗口/拖放/异步文件上传等实用代码
2013/01/06 Javascript
javaScript如何处理从java后台返回的list
2014/04/24 Javascript
js根据鼠标移动速度背景图片自动旋转的方法
2015/02/28 Javascript
Function.prototype.apply()与Function.prototype.call()小结
2016/04/27 Javascript
js实现多图左右切换功能
2016/08/04 Javascript
详解Vue中添加过渡效果
2017/03/20 Javascript
JS求Number类型数组中最大元素方法
2018/04/08 Javascript
使用vue-cli脚手架工具搭建vue-webpack项目
2019/01/14 Javascript
jQuery实现合并表格单元格中相同行操作示例
2019/01/28 jQuery
使用JS判断页面是首次被加载还是刷新
2019/05/26 Javascript
Python脚本处理空格的方法
2016/08/08 Python
Python装饰器用法实例分析
2019/01/14 Python
python批量处理文件或文件夹
2020/07/28 Python
Python pandas如何向excel添加数据
2020/05/22 Python
django使用graphql的实例
2020/09/02 Python
墨西哥网上超市:Superama
2018/07/10 全球购物
eharmony澳大利亚:网上约会服务
2020/02/29 全球购物
"火柴棍式"程序员面试题
2014/03/16 面试题
恒华伟业笔试面试题
2015/02/26 面试题
教师暑期培训感言
2014/08/15 职场文书
安全生产工作汇报材料
2014/10/28 职场文书
亮剑观后感500字
2015/06/05 职场文书
安全责任协议书范本
2016/03/23 职场文书
浅谈如何提高PHP代码的质量
2021/05/28 PHP
Python办公自动化之教你如何用Python将任意文件转为PDF格式
2021/06/28 Python
世界十大狙击步枪排行榜
2022/03/20 杂记