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二叉树的实现实例
Nov 21 Python
Python 分析Nginx访问日志并保存到MySQL数据库实例
Mar 13 Python
Python实现的tab文件操作类分享
Nov 20 Python
python通过定义一个类实例作为ftp回调方法
May 04 Python
Python 功能和特点(新手必学)
Dec 30 Python
Flask模拟实现CSRF攻击的方法
Jul 24 Python
Pycharm取消py脚本中SQL识别的方法
Nov 29 Python
详解python使用turtle库来画一朵花
Mar 21 Python
Python实现根据日期获取当天凌晨时间戳的方法示例
Apr 09 Python
python使用threading.Condition交替打印两个字符
May 07 Python
Python之修改图片像素值的方法
Jul 03 Python
Django Channels 实现点对点实时聊天和消息推送功能
Jul 17 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 字符串编码截取函数(兼容utf-8和gb2312)
2009/05/02 PHP
PHP更新购物车数量(表单部分/PHP处理部分)
2013/05/03 PHP
php检测数组长度函数sizeof与count用法
2014/11/17 PHP
php 访问oracle 存储过程实例详解
2017/01/08 PHP
PHP实现查询手机归属地的方法详解
2017/04/28 PHP
JavaScript实现拼音排序的方法
2012/11/20 Javascript
jQuery实现密保互斥问题解决方案
2013/08/16 Javascript
jquery实现table鼠标经过变色代码
2013/09/25 Javascript
jquery 实现input输入什么div图层显示什么
2014/06/15 Javascript
基于JavaScript操作DOM常用的API小结
2015/12/01 Javascript
JavaScript截取指定长度字符串点击可以展开全部代码
2015/12/04 Javascript
Bootstrap每天必学之附加导航(Affix)插件
2016/04/25 Javascript
全面了解addEventListener和on的区别
2016/07/14 Javascript
在点击div中的p时,如何阻止事件冒泡
2017/02/07 Javascript
详解vuex 中的 state 在组件中如何监听
2017/05/23 Javascript
js实现省市级联效果分享
2017/08/10 Javascript
nodejs实现的连接MySQL数据库功能示例
2018/01/25 NodeJs
jQuery实现的响应鼠标移动方向插件用法示例【附源码下载】
2018/08/28 jQuery
jQuery实现表格的增、删、改操作示例
2019/01/27 jQuery
实用的Vue开发技巧
2019/05/30 Javascript
JavaScript前端页面搜索功能案例【基于jQuery】
2019/07/10 jQuery
Vue 使用计时器实现跑马灯效果的实例代码
2019/07/11 Javascript
python使用mysqldb连接数据库操作方法示例详解
2013/12/03 Python
Python使用百度API上传文件到百度网盘代码分享
2014/11/08 Python
python微信公众号开发简单流程
2018/03/23 Python
python实现维吉尼亚加密法
2019/03/20 Python
Python 复平面绘图实例
2019/11/21 Python
django框架auth模块用法实例详解
2019/12/10 Python
基于HTML5 FileSystem API的使用介绍
2013/04/24 HTML / CSS
女士和男士时尚鞋在线购物:Shoespie
2019/02/28 全球购物
澳大利亚厨房和家用电器购物网站:Bing Lee
2021/01/11 全球购物
ORACLE十问
2015/04/20 面试题
数控技校生自我鉴定
2014/03/02 职场文书
个人贷款担保书
2014/04/01 职场文书
2015年生产部工作总结范文
2015/05/25 职场文书
高三化学教学反思
2016/02/22 职场文书