d639121 2020-04-20 15:05 采纳率: 0%
浏览 3409

求大佬指点 如何解决 python 3.X 报错:'in <string>' requires string as left operand, not bytes

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import socket
import telnetlib


class dubbo:
    # 定义私有属性
    __init = False
    __encoding = "utf8"
    __finish = 'dubbo>'
    __connect_timeout = 10
    __read_timeout = 10

    # 定义构造方法
    def __init__(self, host, port):
        self.host = host
        self.port = port
        if host is not None and port is not None:
            self.__init = True

    def set_finish(self, finish):
        '''
        defualt is ``dubbo>``
        '''
        self.__finish = finish

    def set_encoding(self, encoding):
        '''
        If ``result retured by dubbo`` is a ``str`` instance and is encoded with an ASCII based encoding
        other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
        must be specified. Encodings that are not ASCII based (such as UCS-2)
        are not allowed and should be decoded to ``unicode`` first.
        '''
        self.__encoding = encoding

    def set_connect_timeout(self, timeout):
        '''
        Defines a timeout for establishing a connection with a dubbo server.
        It should be noted that this timeout cannot usually exceed 75 seconds.

        defualt is ``10``
        '''
        self.__connect_timeout = timeout

    def set_read_timeout(self, timeout):
        '''
        Defines a timeout for reading a response expected from the dubbo server.

        defualt is ``10``
        '''
        self.__read_timeout = timeout

    def do(self, command):
        # 连接Telnet服务器
        try:
            tn = telnetlib.Telnet(host=self.host, port=self.port, timeout=self.__connect_timeout)
        except socket.error as err:
            print("[host:%s port:%s] %s" % (self.host, self.port, err))
            return

        # 触发doubble提示符
        tn.write('\n')

        # 执行命令
        tn.read_until(self.__finish, timeout=self.__read_timeout)
        tn.write('%s\n' % command)

        # 获取结果
        data = ''
        while data.find(self.__finish) == -1:
            data = tn.read_very_eager()
        data = data.split("\n")
        data = json.loads(data[0], encoding=self.__encoding)

        tn.close()  # tn.write('exit\n')

        return data

    def invoke(self, interface, method, param):
        cmd = "%s %s.%s(%s)" % ('invoke', interface, method, param)
        return self.do(cmd)


def connect(host, port):
    return dubbo(host, port)


if __name__ == '__main__':
    Host = '192.168.0.56'  # Doubble服务器IP
    Port = 20884  # Doubble服务端口

    # 初始化dubbo对象
    conn = dubbo(Host, Port)

    # 设置telnet连接超时时间
    conn.set_connect_timeout(10)

    # 设置dubbo服务返回响应的编码
    conn.set_encoding('utf-8')

    interface = 'com.tz.course.stub.service.ICoursePackageFacadeAPI'
    method = 'checkCourseStatusByCourseIds'
    param = '{"courseIds": "9765", "userId": "56645"}'
    # print(conn.invoke(interface, method, param))

    command = 'invoke com.tz.course.stub.service.ICoursePackageFacadeAPI.checkCourseStatusByCourseIds({"courseIds": "9765", "userId": "56645"})'
    # print(conn.do(command))

#coding=utf8
import sys
from kazoo.client import KazooClient
import urllib
import urllib3
import json
import telnetlib
import socket
import dubbo_telnet

Host = '172.16.68.161:2181'  # zookeeper的地址

def coondoubble_data(servhost, servport,interface,method,param):
    try:
        # 初始化dubbo对象
        conn = dubbo_telnet.connect(servhost, servport)
        # 设置telnet连接超时时间
        conn.set_connect_timeout(10)
        # 设置dubbo服务返回响应的编码
        conn.set_encoding('utf-8')
        data=conn.invoke(interface, method, param)
        return data
    except Exception as e:
        return  e

def get_dubbo_full():
    global Host
    zk = KazooClient(hosts="{}".format(Host))
    zk.start()
    urls = []
    list = zk.get_children("dubbo")
    for i in list:
        if 'serv' in i: #关键字过滤
            # print i
            try:
                gg = zk.get_children("/dubbo/{}/providers".format(i))
                if gg:
                    for j in gg:
                        url = urllib.parse.unquote(j)
                        if url.startswith('dubbo:'):
                            urls.append(url.split('?')[0].split('dubbo://')[1])
            except Exception as e:
                print(e)
                print(i)
    services = {}
    for i in urls:
        try:
            path, service = i.split('/')
            if not services.get(path):
                services.update({path: []})
            services[path].append(service)
        except Exception as e:
            pass
    print(json.dumps(services, indent=4))

def get_dubbo(servername):
    global Host
    zk = KazooClient(hosts="{}".format(Host))
    zk.start()
    urls = []
    list = zk.get_children("dubbo")
    for i in list:
        if servername in i:
            try:
                # 获取服务发布方
                gg = zk.get_children("/dubbo/{}/providers".format(i))
                if gg:
                    for j in gg:
                        url = urllib.parse.unquote(j)
                        if url.startswith('dubbo:'):
                            urls.append(url.split('dubbo://')[1])
            except Exception as e:
                print(e)
    paths=[]
    for i in urls:
        try:
            path, temp = i.split('/')
            service=temp.split('?')[0]
            method=temp.split('methods=')[1].split('&')[0].split(',')
            paths.append(path)
        except Exception as e:
            print(e)
    services = {"service": service, "paths": paths, "method": method}
    return services
    print(json.dumps(services, indent=4))

if __name__ == '__main__':
    #使用方法get_dubbo('<服务名>')
    # get_dubbo('com.serv.finance.service.CommReimQueryService__1_0')
    #get_dubbo('com.tz.edu.power.stub.AccessTuneLogAPI')

     param='''{"batSubmitId":null, "logonId":"8ybbmd01.c.0200", "len":"20", "groupId":"020090006110982", "start":"0", "logonLevel":"3", "limitSum1":"40000", "limitSum":"90000000000000000", "endTime":"20200101", "beginTime":"20190101", "batFileName":null, "channelFlag":"1"}'''
    # #使用方法coondoubble_data('服务提供者ip','服务提供者port','服务名','调用方法','发送数据')
    # #'服务提供者ip','服务提供者port','服务名','调用方法'从get_dubbo()返回结果中获取
     resp=coondoubble_data("192.168.1.100", "35009", "com.serv.finance.service.CommReimQueryService__1_0", "commReimQueryBatch", param)
     print(resp)

  • 写回答

3条回答 默认 最新

  • 吃鸡王者 2020-04-20 16:16
    关注

    感觉有个地方没有解码,你贴的代码不全吧?

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划