兼容python3的SSDB客户端

SSDB.py

import socket

class SSDB_Response(object):
    def __init__(self, code=‘‘, data_or_message=None):
        self.type = ‘none‘
        self.code = code
        self.data = None
        self.message = None
        self.set(code, data_or_message)

    def set(self, code, data_or_message=None):
        self.code = code

        if code == ‘ok‘:
            self.data = data_or_message
        else:
            if isinstance(data_or_message, list):
                if len(data_or_message) > 0:
                    self.message = data_or_message[0]
            else:
                self.message = data_or_message

    def __repr__(self):
        return ((((str(self.code) + ‘ ‘) + str(self.message)) + ‘ ‘) + str(self.data))

    def ok(self):
        return self.code == ‘ok‘

    def not_found(self):
        return self.code == ‘not_found‘

    def str_resp(self, resp):
        self.type = ‘val‘

        if resp[0] == ‘ok‘:
            if len(resp) == 2:
                self.set(‘ok‘, resp[1])
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            self.set(resp[0], resp[1:])
        return self

    def str_resp(self, resp):
        self.type = ‘val‘
        if resp[0] == ‘ok‘:
            if len(resp) == 2:
                self.set(‘ok‘, resp[1])
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            self.set(resp[0], resp[1:])
        return self

    def int_resp(self, resp):
        self.type = ‘val‘

        if resp[0] == ‘ok‘:
            if len(resp) == 2:
                try:
                    val = int(resp[1])
                    self.set(‘ok‘, val)
                except Exception as e:
                    self.set(‘server_error‘, ‘Invalid response‘)
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            pass
            self.set(resp[0], resp[1:])
        return self

    def float_resp(self, resp):
        self.type = ‘val‘
        if resp[0] == ‘ok‘:
            if len(resp) == 2:
                try:
                    val = float(resp[1])
                    self.set(‘ok‘, val)
                except Exception as e:
                    self.set(‘server_error‘, ‘Invalid response‘)
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            self.set(resp[0], resp[1:])
        return self

    def list_resp(self, resp):
        self.type = ‘list‘
        self.set(resp[0], resp[1:])
        return self

    def int_map_resp(self, resp):
        self.type = ‘map‘

        if resp[0] == ‘ok‘:
            if len(resp) % 2 == 1:
                data = {‘index‘: [], ‘items‘: {}, }
                i = 1

                while i < len(resp):
                    k = resp[i]
                    v = resp[(i + 1)]
                    try:
                        v = int(v)
                    except Exception as e:
                        v = - (1)
                    data[‘index‘].append(k)
                    data[‘items‘][k] = v
                    i += 2
                self.set(‘ok‘, data)
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            self.set(resp[0], resp[1:])
        return self

    def str_map_resp(self, resp):
        self.type = ‘map‘

        if resp[0] == ‘ok‘:

            if len(resp) % 2 == 1:
                data = {‘index‘: [], ‘items‘: {}, }
                i = 1

                while i < len(resp):
                    k = resp[i]
                    v = resp[(i + 1)]
                    data[‘index‘].append(k)
                    data[‘items‘][k] = v
                    i += 2
                self.set(‘ok‘, data)
            else:
                self.set(‘server_error‘, ‘Invalid response‘)
        else:
            self.set(resp[0], resp[1:])
        return self

class SSDB(object):
    def __init__(self, host, port):
        self.recv_buf = ‘‘
        self._closed = False
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect(tuple([host, port]))
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

    def close(self):
        if not (self._closed):
            self.sock.close()
            self._closed = True

    def closed(self):
        pass
        return self._closed

    def request(self, cmd, params=None):
        pass

        if params is None:
            params = []
        params = ([cmd] + params)
        self.send(params)
        resp = self.recv()

        if resp is None:
            return SSDB_Response(‘error‘, ‘Unknown error‘)

        if len(resp) == 0:
            return SSDB_Response(‘disconnected‘, ‘Connection closed‘)
        ret = SSDB_Response()

        # {{{ switch: cmd
        _continue_1 = False
        while True:
            if False or ((cmd) == ‘ping‘) or ((cmd) == ‘set‘) or ((cmd) == ‘del‘) or ((cmd) == ‘qset‘) or (
                (cmd) == ‘zset‘) or ((cmd) == ‘hset‘) or ((cmd) == ‘qpush‘) or ((cmd) == ‘qpush_front‘) or (
                (cmd) == ‘qpush_back‘) or ((cmd) == ‘zdel‘) or ((cmd) == ‘hdel‘) or ((cmd) == ‘multi_set‘) or (
                (cmd) == ‘multi_del‘) or ((cmd) == ‘multi_hset‘) or ((cmd) == ‘multi_hdel‘) or (
                (cmd) == ‘multi_zset‘) or ((cmd) == ‘multi_zdel‘):
                if len(resp) > 1:
                    return ret.int_resp(resp)
                else:
                    return SSDB_Response(resp[0], None)
                break
            if False or ((cmd) == ‘version‘) or ((cmd) == ‘substr‘) or ((cmd) == ‘get‘) or ((cmd) == ‘getset‘) or (
                (cmd) == ‘hget‘) or ((cmd) == ‘qfront‘) or ((cmd) == ‘qback‘) or ((cmd) == ‘qget‘):
                pass
                return ret.str_resp(resp)
                break
            if False or ((cmd) == ‘qpop‘) or ((cmd) == ‘qpop_front‘) or ((cmd) == ‘qpop_back‘):
                size = 1
                try:
                    size = int(params[2])
                except Exception as e:
                    pass

                if size == 1:
                    return ret.str_resp(resp)
                else:
                    return ret.list_resp(resp)
                break
            if False or ((cmd) == ‘dbsize‘) or ((cmd) == ‘getbit‘) or ((cmd) == ‘setbit‘) or ((cmd) == ‘countbit‘) or (
                (cmd) == ‘bitcount‘) or ((cmd) == ‘strlen‘) or ((cmd) == ‘ttl‘) or ((cmd) == ‘expire‘) or (
                (cmd) == ‘setnx‘) or ((cmd) == ‘incr‘) or ((cmd) == ‘decr‘) or ((cmd) == ‘zincr‘) or (
                (cmd) == ‘zdecr‘) or ((cmd) == ‘hincr‘) or ((cmd) == ‘hdecr‘) or ((cmd) == ‘hsize‘) or (
                (cmd) == ‘zsize‘) or ((cmd) == ‘qsize‘) or ((cmd) == ‘zget‘) or ((cmd) == ‘zrank‘) or (
                (cmd) == ‘zrrank‘) or ((cmd) == ‘zsum‘) or ((cmd) == ‘zcount‘) or ((cmd) == ‘zremrangebyrank‘) or (
                (cmd) == ‘zremrangebyscore‘) or ((cmd) == ‘hclear‘) or ((cmd) == ‘zclear‘) or ((cmd) == ‘qclear‘) or (
                (cmd) == ‘qpush‘) or ((cmd) == ‘qpush_front‘) or ((cmd) == ‘qpush_back‘) or (
                (cmd) == ‘qtrim_front‘) or ((cmd) == ‘qtrim_back‘):
                pass
                return ret.int_resp(resp)
                break
            if False or ((cmd) == ‘zavg‘):
                pass
                return ret.float_resp(resp)
                break
            if False or ((cmd) == ‘keys‘) or ((cmd) == ‘rkeys‘) or ((cmd) == ‘zkeys‘) or ((cmd) == ‘zrkeys‘) or (
                (cmd) == ‘hkeys‘) or ((cmd) == ‘hrkeys‘) or ((cmd) == ‘list‘) or ((cmd) == ‘hlist‘) or (
                (cmd) == ‘hrlist‘) or ((cmd) == ‘zlist‘) or ((cmd) == ‘zrlist‘):
                pass
                return ret.list_resp(resp)
                break
            if False or ((cmd) == ‘scan‘) or ((cmd) == ‘rscan‘) or ((cmd) == ‘hgetall‘) or ((cmd) == ‘hscan‘) or (
                (cmd) == ‘hrscan‘):
                pass
                return ret.str_map_resp(resp)
                break
            if False or ((cmd) == ‘zscan‘) or ((cmd) == ‘zrscan‘) or ((cmd) == ‘zrange‘) or ((cmd) == ‘zrrange‘) or (
                (cmd) == ‘zpop_front‘) or ((cmd) == ‘zpop_back‘):
                pass
                return ret.int_map_resp(resp)
                break
            if False or ((cmd) == ‘auth‘) or ((cmd) == ‘exists‘) or ((cmd) == ‘hexists‘) or ((cmd) == ‘zexists‘):
                pass
                return ret.int_resp(resp)
                break
            if False or ((cmd) == ‘multi_exists‘) or ((cmd) == ‘multi_hexists‘) or ((cmd) == ‘multi_zexists‘):
                pass
                return ret.int_map_resp(resp)
                break
            if False or ((cmd) == ‘multi_get‘) or ((cmd) == ‘multi_hget‘):
                pass
                return ret.str_map_resp(resp)
                break
            if False or ((cmd) == ‘multi_hsize‘) or ((cmd) == ‘multi_zsize‘) or ((cmd) == ‘multi_zget‘):
                pass
                return ret.int_map_resp(resp)
                break
            ### default
            return ret.list_resp(resp)
            break
            break
            if _continue_1:
                continue
        # }}} switch

        return SSDB_Response(‘error‘, ‘Unknown error‘)

    def send(self, data):
        pass
        ps = []

        _cpy_r_0 = _cpy_l_1 = data
        if type(_cpy_r_0).__name__ == ‘dict‘:
            _cpy_b_3 = True; _cpy_l_1 = _cpy_r_0.iterkeys()
        else:
            _cpy_b_3 = False;
        for _cpy_k_2 in _cpy_l_1:
            if _cpy_b_3:
                p = _cpy_r_0[_cpy_k_2]
            else:
                p = _cpy_k_2
            pass
            p = str(p)
            ps.append(str(len(p)))
            ps.append(p)
        nl = ‘\n‘
        s = (nl.join(ps) + ‘\n\n‘)
        try:
            while True:
                ret = self.sock.send(s.encode())
                if ret == 0:
                    return - (1)
                s = s[ret:]
                if len(s) == 0:
                    break
        except socket.error as e:
            return -(1)
        return ret

    def net_read(self):
        try:
            data = self.sock.recv(1024 * 8)
        except Exception as e:
            data = ‘‘

        if data == ‘‘:
            self.close()
            return 0
        self.recv_buf += str(data,encoding = "ascii")
        return len(data)

    def recv(self):
        while True:
            ret = self.parse()
            if ret is None:
                if self.net_read() == 0:
                    return []
            else:
                return ret

    def parse(self):
        pass
        ret = []
        spos = 0
        epos = 0

        while True:
            spos = epos
            epos = self.recv_buf.find(‘\n‘, spos)

            if epos == - (1):
                break
            epos += 1
            line = self.recv_buf[spos: epos]
            spos = epos

            if line.strip() == ‘‘:
                if len(ret) == 0:
                    continue
                else:
                    self.recv_buf = self.recv_buf[spos:]
                    return ret
            try:
                num = int(line)
            except Exception as e:
                return []
            epos = (spos + num)

            if epos > len(self.recv_buf):
                break
            data = self.recv_buf[spos: epos]
            ret.append(data)
            spos = epos
            epos = self.recv_buf.find(‘\n‘, spos)

            if epos == - (1):
                break
            epos += 1
        return None

测试程序

from SSDB import SSDB

ssdb = SSDB(‘192.168.1.250‘, 8888)

l  =  []
l.append(‘person_1‘)
l.append(‘a‘)
l.append(‘1111‘)
l.append(‘b‘)
l.append(‘2222‘)

print(ssdb.request(‘multi_hset‘, l))

‘‘‘
print(ssdb.request(‘set‘, [‘test‘, ‘123‘]))
print(ssdb.request(‘get‘, [‘test‘]))
print(ssdb.request(‘incr‘, [‘test‘, ‘1‘]))
print(ssdb.request(‘decr‘, [‘test‘, ‘1‘]))
print(ssdb.request(‘scan‘, [‘a‘, ‘z‘, 10]))
print(ssdb.request(‘rscan‘, [‘z‘, ‘a‘, 10]))
print(ssdb.request(‘keys‘, [‘a‘, ‘z‘, 10]))
print(ssdb.request(‘del‘, [‘test‘]))
print(ssdb.request(‘get‘, [‘test‘]))
print("\n")
print(ssdb.request(‘zset‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘zget‘, [‘test‘, ‘a‘]))
print(ssdb.request(‘zincr‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘zdecr‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘zscan‘, [‘test‘, ‘a‘, 0, 100, 10]))
print(ssdb.request(‘zrscan‘, [‘test‘, ‘a‘, 100, 0, 10]))
print(ssdb.request(‘zkeys‘, [‘test‘, ‘a‘, 0, 100, 10]))
print(ssdb.request(‘zdel‘, [‘test‘, ‘a‘]))
print(ssdb.request(‘zget‘, [‘test‘, ‘a‘]))
print("\n")
print(ssdb.request(‘hset‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘hget‘, [‘test‘, ‘a‘]))
print(ssdb.request(‘hincr‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘hdecr‘, [‘test‘, ‘a‘, 20]))
print(ssdb.request(‘hscan‘, [‘test‘, ‘0‘, ‘z‘, 10]))
print(ssdb.request(‘hrscan‘, [‘test‘, ‘z‘, ‘0‘, 10]))
print(ssdb.request(‘hkeys‘, [‘test‘, ‘0‘, ‘z‘, 10]))
print(ssdb.request(‘hdel‘, [‘test‘, ‘a‘]))
print(ssdb.request(‘hget‘, [‘test‘, ‘a‘]))
print("\n")
‘‘‘
时间: 2024-10-14 19:39:54

兼容python3的SSDB客户端的相关文章

python3中实现客户端与服务端交互发送文件

在python3中实现客户端与服务端程序交互,从客户端发送文件到服务端 客户端代码:client.py #!/usr/bin/env python #_*_ encoding=utf-8 _*_ import socket,sys,os ip_port = ('127.0.0.1',9999) sk = socket.socket() sk.connect(ip_port) container = {'key':'','data':''} while True:     input_data =

让你的python程序同时兼容python2和python3

python邮件列表里有人发表言论说「python3在10内都无法普及」.在我看来这样的观点有些过于悲观,python3和python2虽然不兼容,但他们之间差别并没很多人想像的那么大.你只需要对自己的代码稍微做些修改就可以很好的同时支持python2和python3的.下面我将简要的介绍一下如何让自己的python代码如何同时支持python2和python3.放弃python 2.6之前的python版本python 2.6之前的python版本缺少一些新特性,会给你的迁移工作带来不少麻烦.

python3实现的rtsp客户端脚本

一.说明 此客户端使用python3编写 此客户端实现RTSP的OPTIONS, DESCRIBE, SETUP , PLAY, GET_PARAMETER,TEARDOWN方法,未实现SET_PARAMETER方法(因为不懂怎么才能生成这个请求没拦截到数据包) RTSP有且只有以上7种请求,而且基本是对同一URI依次执行以上7种请求:或者说RTSP就是"7种请求"+"1个URL",如果想做渗透测试也就针对这"7+1"做参数溢出测试,没很多可测的

Python2与Python3兼容

Python2与Python3兼容 python3写的代码如何也能在pyhon2上跑?请无论如何加上这一句,python3没有啥影响 from __future__ import absolute_import, unicode_literals, division, print_function __future__模块提供某些将要引入的特性,python 2.7.5的__future__基本上是python3中的特性 开始 使用我们的jupyter交互式工具进行探讨,以下皆为python2

跨平台轻量级redis、ssdb代理服务器(C++ 11编写)

dbproxy 是我业余采用C++11编写的跨平台代理服务器(并使用lua和自己的网络库),以扩展系统负载,同时使用多个后端数据库,后端数据库支持redis和ssdb. 需要由用户自己编写lua脚本控制sharding.测试效率比codis略高,且占用更少的CPU和内存. 下面是github上的readme,我直接拷贝下来: 介绍 dbproxy是一个采用C++11编写的代理服务器,支持redis和 ssdb数据库. 其主要用于扩容和提高系统负载.使用lua控制sharding,把不同的key-

python3.4 or 3.x xlwt replaced with xlwt-future

Q:最近在使用python3.4处理一些生物信息数据,需要将内容保存到excel中,但是,但是,发现xlwt不能再3.4中使用,即使安装也安装不成功. 由于xlwt不兼容python3.4(x),不必要使用pip或者easy_install-3.4无味的尝试了 差点因此放弃python,使用perl(其实Perl很熟悉,以前(一个月2014.09.01之前还是常用的) A: https://pypi.python.org/pypi/xlwt-future下载+解压+ admin:~/Downlo

IE11 不兼容

IE11不兼容,可以通过客户端设置IE的兼容性     选择“兼容性视图设置”然后添加需要兼容的地址 将网站发布到IIS上,可以通过在Web.config中的<system.webServer>中添加代码 <directoryBrowse enabled="true" /> <httpProtocol> <customHeaders> <clear /> <add name="X-UA-Compatible&q

Python3和Django如何支持MySQL和MariaDB数据库

原文地址:http://www.server110.com/mariadb/201404/10020.html 首先,[email protected] 中默认的引擎为 django.db.backends.mysql .但是在Python3中如果这样写的话,会发现 django.db.backends.mysql 依赖 MySQLdb[5] ,而 MySQLdb 又不兼容 Python3 于是要找一种新的方式来继续使用MySQL. 首先据MySQL文档[3]说,自从MySQL Connecto

Python3 字符串前面加u,r,b的含义

u/U:表示unicode字符串 不是仅仅是针对中文, 可以针对任何的字符串,代表是对字符串进行unicode编码. 一般英文字符在使用各种编码下, 基本都可以正常解析, 所以一般不带u:但是中文, 必须表明所需编码, 否则一旦编码转换就会出现乱码. 建议所有编码方式采用utf8.在python3中,字符串默认为unicode字符串. 例子: u"我是含有中文字符组成的字符串." 作用: 后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导