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读写文本文件及编写简单的文本编辑器
Mar 11 Python
python遍历目录的方法小结
Apr 28 Python
python中set常用操作汇总
Jun 30 Python
Python切片操作深入详解
Jul 27 Python
对python Tkinter Text的用法详解
Oct 11 Python
Python利用requests模块下载图片实例代码
Aug 12 Python
Django REST框架创建一个简单的Api实例讲解
Nov 05 Python
centos7中安装python3.6.4的教程
Dec 11 Python
Python爬虫库requests获取响应内容、响应状态码、响应头
Jan 25 Python
python isinstance函数用法详解
Feb 13 Python
python怎么提高计算速度
Jun 11 Python
scrapy-splash简单使用详解
Feb 21 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
PHP 和 XML: 使用expat函数(三)
2006/10/09 PHP
zf框架的校验器使用使用示例(自定义校验器和校验器链)
2014/03/13 PHP
ThinkPHP静态缓存简单配置和使用方法详解
2016/03/23 PHP
BOOM vs RR BO5 第三场 2.14
2021/03/10 DOTA
JavaScript中的其他对象
2008/01/16 Javascript
js 窗口抖动示例
2013/09/04 Javascript
JSON序列化与解析原生JS方法且IE6和chrome测试通过
2013/09/05 Javascript
javascript通过navigator.userAgent识别各种浏览器
2013/10/25 Javascript
jquery.mobile 共同布局遇到的问题小结
2015/02/10 Javascript
教你使用javascript简单写一个页面模板引擎
2015/05/05 Javascript
jQuery实现ajax调用WCF服务的方法(附带demo下载)
2015/12/04 Javascript
学习JavaScript设计模式之单例模式
2016/01/19 Javascript
原生javascript实现图片无缝滚动效果
2016/02/12 Javascript
ArtEditor富文本编辑器增加表单提交功能
2016/04/18 Javascript
web前端开发upload上传头像js示例代码
2016/10/22 Javascript
js实现自动轮换选项卡
2017/01/13 Javascript
微信小程序实现顶部选项卡(swiper)
2020/06/19 Javascript
ES6 javascript中class类的get与set用法实例分析
2017/10/30 Javascript
jquery+ajaxform+springboot控件实现数据更新功能
2018/01/22 jQuery
Vue 实现点击空白处隐藏某节点的三种方式(指令、普通、遮罩)
2019/10/23 Javascript
JQuery使用属性addClass、removeClass和toggleClass实现增加和删除类操作示例
2019/11/18 jQuery
解决vue+router路由跳转不起作用的一项原因
2020/07/19 Javascript
python fabric使用笔记
2015/05/09 Python
Python使用urllib2模块实现断点续传下载的方法
2015/06/17 Python
python 递归遍历文件夹,并打印满足条件的文件路径实例
2017/08/30 Python
python接口自动化之ConfigParser配置文件的使用详解
2020/08/03 Python
python安装mysql的依赖包mysql-python操作
2021/01/01 Python
美国在线艺术商店:HandmadePiece
2020/11/06 全球购物
接口可以包含哪些成员
2012/09/30 面试题
研发工程师的岗位职责
2013/11/18 职场文书
电子商务专业学生的自我鉴定
2013/11/28 职场文书
会计自荐书
2013/12/02 职场文书
推广普通话宣传标语口号
2015/12/26 职场文书
Apache Pulsar结合Hudi构建Lakehouse方案分析
2022/03/31 Servers
忘记Grafana不要紧2种Grafana重置admin密码方法详细步骤
2022/04/07 Servers
win11开机发生死循环重启怎么办?win11开机发生死循环重启解决方法
2022/08/05 数码科技