[雪峰磁针石博客]python工具库介绍-dubbo:通过telnet接口访问dubbo服务

简介: Django - The Easy Way pdf - 2017 [下载地址](https://itbooks.pipipan.com/fs/18113597-305049783) Django is a very powerful Python Web Framework.
## 简介

dubbo服务发布之后,我们可以利用telnet命令进行调试、管理。更多资料参见 [Telnet命令参考手册](http://alibaba.github.io/dubbo-doc-static/Telnet+Command+Reference-zh-showComments=true&showCommentArea=true.htm)

telnet 调用示例:


```python

$ telnet 172.17.103.110 9097
Trying 172.17.103.110...
Connected to 172.17.103.110.
Escape character is '^]'.

dubbo>ls com.oppo.sso.service.onekey.IOnekeyRegister
register
dubbo>invoke com.oppo.sso.service.onekey.IOnekeyRegister.register({"applicationKey":"mac","imei":"","mobile":"13244448888","createIP":"127.0.0.1","createBy":"172.17.0.1"})
{"configCountry":null,"userIdLong":0,"appPackage":null,"appVersion":null,"accountName":null,"romVersion":null,"resultCode":3001,"thirdStatus":null,"registerType":0,"sendChannel":null,"operator":null,"manufacturer":null,"password":null,"osVersion":null,"lock":false,"model":null,"visitorLocked":false,"OK":false,"brand":null,"email":null,"createIP":null,"deny":false,"encryptEmail":null,"sessionKey":null,"thirdId":null,"passwordOriginal":null,"mobile":null,"applicationKey":null,"thirdpartyOk":false,"userAgent":null,"userName":null,"resultDesc":"应用不存在","userId":0,"encryptMobile":null,"emailStatus":null,"createBy":null,"freePwd":false,"changeTimes":0,"createTime":null,"mobileStatus":null,"oldLock":false,"codeTimeout":null,"lastUpdate":null,"imei":null,"sessionTimeout":0,"sdkVersion":null,"networkID":0,"status":null}
elapsed: 98 ms.
dubbo>

```

## Python实现

源码:


```python

"""
Name: dubbo.py

Tesed in python3.5
"""

import json
import telnetlib
import socket


class Dubbo(telnetlib.Telnet):

    prompt = 'dubbo>'
    coding = 'utf-8'

    def __init__(self, host=None, port=0,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        super().__init__(host, port)
        self.write(b'\n')

    def command(self, flag, str_=""):
        data = self.read_until(flag.encode())
        self.write(str_.encode() + b"\n")
        return data

    def invoke(self, service_name, method_name, arg):
        command_str = "invoke {0}.{1}({2})".format(
            service_name, method_name, json.dumps(arg))
        self.command(Dubbo.prompt, command_str)
        data = self.command(Dubbo.prompt, "")
        data = json.loads(data.decode(Dubbo.coding,
                                      errors='ignore').split('\n')[0].strip())
        return data

if __name__ == '__main__':

    conn = Dubbo('172.17.103.110', 9097)

    json_data = {
        "applicationKey":"mac",
        "imei":"",
        "mobile":"13244448888",
        "createIP":"127.0.0.1",
        "createBy":"172.17.0.1"
    }

    result = conn.invoke(
        "com.oppo.sso.service.onekey.IOnekeyRegister",
        "register",
        json_data
    )
    print(result)
```

执行结果:


```python

# python3 dubbo.py
{'manufacturer': None, 'applicationKey': None, 'OK': False, 'codeTimeout': None, 'password': None, 'encryptEmail': None, 'passwordOriginal': None, 'thirdId': None, 'emailStatus': None, 'freePwd': False, 'sessionTimeout': 0, 'createTime': None, 'osVersion': None, 'lastUpdate': None, 'email': None, 'sdkVersion': None, 'registerType': 0, 'sendChannel': None, 'visitorLocked': False, 'createIP': None, 'thirdStatus': None, 'encryptMobile': None, 'networkID': 0, 'resultCode': 3001, 'brand': None, 'changeTimes': 0, 'userAgent': None, 'imei': None, 'operator': None, 'romVersion': None, 'model': None, 'lock': False, 'sessionKey': None, 'configCountry': None, 'deny': False, 'userIdLong': 0, 'resultDesc': '应用不存在', 'status': None, 'createBy': None, 'thirdpartyOk': False, 'appPackage': None, 'appVersion': None, 'accountName': None, 'userId': 0, 'oldLock': False, 'userName': None, 'mobile': None, 'mobileStatus': None}
```


更复杂的例子。

源码:


```python

import json
import telnetlib
import socket


class Dubbo(telnetlib.Telnet):

    prompt = 'dubbo>'
    coding = 'gbk'

    def __init__(self, host=None, port=0,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        super().__init__(host, port)
        self.write(b'\n')

    def command(self, flag, str_=""):
        data = self.read_until(flag.encode())
        self.write(str_.encode() + b"\n")
        return data

    def invoke(self, service_name, method_name, arg):
        command_str = "invoke {0}.{1}({2})".format(
            service_name, method_name, json.dumps(arg))
        self.command(Dubbo.prompt, command_str)
        data = self.command(Dubbo.prompt, "")
        data = json.loads(data.decode(Dubbo.coding,
                                      errors='ignore').split('\n')[0].strip())
        return data

if __name__ == '__main__':

    conn = Dubbo('183.131.22.99', 21881)

    content = {
        "sign": "FKeKnMEPybHujjBTzz11BrulB5av7pLhJpk=",
        "partnerOrder": "0511e0d38f334319a96920fa02be02a7",
        "productDesc": "hello",
        "paySuccessTime": "2016-08-25 18:33:04",
        "price": "1",
        "count": "1",
        "attach": "from_pay_demo",
        "date": "20160825",
    }
    content_json = json.dumps(content).replace('"', '\\"')

    json_data = {
        "requestId": "0511e0d38f334319a96920fa02be02a7",
        "reqUrl": 'http://www.oppo.com',
        "httpReqType": "POST",
        "headerMap": None,
        "reqContent": content_json,
        "appId": "10001",
        "productName": "test",
        "timeStamp": "1472121184957",
        "partnerId": "2031",
        "signType": "MD5",
        "sign": "23B621FBBF887373C65E553C2222258F",
        "successResult": "OK",
    }

    result = conn.invoke(
        "com.oppo.pay.notify.api.facade.NotifyApplyService",
        "httpNotify",
        json_data
    )
    print(result)
```

执行结果:


```python

$ python3 dubbo.py
{'resMsg': 'ǩ', 'data': None, 'errorDetail': 'sign check fail!', 'resCode': '100003', 'success': False}

```

## 待改进

* 进行多个项目的实验,增加异常处理

## 参考资料

-   [本文最新版本地址](https://china-testing.github.io/python3_lib_dubbo.html)
-   [本文涉及的python测试开发库](https://github.com/china-testing/python-api-tesing) 谢谢点赞!
-   [本文相关海量书籍下载](https://github.com/china-testing/python-api-tesing/blob/master/books.md)
-   [本文源码地址](https://github.com/china-testing/python-api-tesing/tree/master/python3_libraries/_dubbo)


相关文章
|
19天前
|
NoSQL Unix 网络安全
【Azure Cache for Redis】Python Django-Redis连接Azure Redis服务遇上(104, 'Connection reset by peer')
【Azure Cache for Redis】Python Django-Redis连接Azure Redis服务遇上(104, 'Connection reset by peer')
【Azure Cache for Redis】Python Django-Redis连接Azure Redis服务遇上(104, 'Connection reset by peer')
|
19天前
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
|
30天前
|
前端开发 搜索推荐 JavaScript
"揭秘!Python高手如何用Sphinx玩转个人博客?从零搭建,美到犯规,技术干货一网打尽,让你的博客秒变网红级存在!"
【8月更文挑战第14天】Sphinx是Python社区中用于编写和技术分享的强大工具,以其易用性和美观的文档输出著称。本文介绍如何用Sphinx打造个性化博客。首先需安装Python、Sphinx及sphinx_rtd_theme主题。接着通过`sphinx-quickstart`命令初始化项目并配置基本选项。在`conf.py`中可自定义博客元信息和主题设置。
34 3
|
1月前
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
Azure 容器实例(Azure Container Instances,简称 ACI)是一个无服务器容器解决方案,允许用户在 Azure 云环境中运行 Docker 容器,而无需设置虚拟机、集群或编排器。 ACI 适用于任何可以在隔离容器中操作的场景,包括事件驱动的应用程序、从容器开发管道快速部署、数据处理和生成作业。
|
1月前
|
Python
[python]使用gunicorn部署fastapi服务
[python]使用gunicorn部署fastapi服务
|
15天前
|
数据可视化 Python
通过python建立一个web服务查看服务器上的文本、图片、视频等文件
通过python建立一个web服务查看服务器上的文本、图片、视频等文件
16 0
|
21天前
|
NoSQL 网络安全 Redis
用python安装redis并设置服务自启
用python安装redis并设置服务自启
14 0
|
29天前
|
API Python
在线问诊 Python、FastAPI、Neo4j — 提供咨询接口服务
在线问诊 Python、FastAPI、Neo4j — 提供咨询接口服务
28 0
|
1月前
|
Python
[python]使用gunicorn部署fastapi服务
【8月更文挑战第6天】以下是使用`gunicorn`部署`FastAPI`服务的简要步骤:首先安装`FastAPI`与`gunicorn`;创建一个简单的`FastAPI`应用,例如定义根路径返回"Hello World";保存代码为`main.py`;在应用目录中启动`gunicorn`服务,如`gunicorn main:app -w 4 -b 0.0.0.0:8000`,其中`-w 4`指定4个工作进程,`-b`绑定至所有IP的8000端口。这样就完成了基础部署,可通过`http://服务器IP:8000/`访问应用。