2019年07月30日 14:59:29 Shower稻草人 阅读数 25更多

分类专栏: Python
 
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。

0x00

首先需要安装python的thrift包

sudo pip install thrift
  • 1

0x01

编写一个简单接IDL文件helloworld.thrift

const string HELLO_WORLD = "world"

service HelloWorld {
void ping(),
string sayHello(),
string sayMsg(1:string msg)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

thrift脚本通过Thrift编辑器生成所要求的python开发语言代码。即:

thrift -r --gen py helloworld.thrift
  • 1

生成gen-py目录:

├── gen-py
│ ├── helloworld
│ │ ├── constants.py
│ │ ├── HelloWorld.py
│ │ ├── HelloWorld-remote
│ │ ├── __init__.py
│ │ └── ttypes.py
│ └── __init__.py
└── helloworld.thrift
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

0x02

Thrift是一个典型的CS结构,客户端和服务端可以使用不同的语言开发。本文以python为例:
PythonServer.py

import sys
sys.path.append('./gen-py') from helloworld import HelloWorld
from helloworld.ttypes import * from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer import socket class HelloWorldHandler:
def __init__(self):
self.log = {} def ping(self):
print "ping()" def sayHello(self):
print "sayHello()"
return "say hello from " + socket.gethostbyname(socket.gethostname()) def sayMsg(self, msg):
print "sayMsg(" + msg + ")"
return "say " + msg + " from " + socket.gethostbyname(socket.gethostname()) handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1',30303)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "Starting python server..."
server.serve()
print "done!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

PythonClient.py

import sys
sys.path.append('./gen-py') from helloworld import HelloWorld
from helloworld.ttypes import *
from helloworld.constants import * from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol try:
# Make socket
transport = TSocket.TSocket('127.0.0.1', 30303) # Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder
client = HelloWorld.Client(protocol) # Connect!
transport.open() client.ping()
print "ping()" msg = client.sayHello()
print msg
msg = client.sayMsg(HELLO_WORLD)
print msg
transport.close() except Thrift.TException, tx:
print "%s" % (tx.message)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

当前目录结构:

├── gen-py
├── helloworld.thrift
├── PythonClient.py
└── PythonServer.py
  • 1
  • 2
  • 3
  • 4

0x03

运行server端:

$ python PythonServer.py
Starting python server...
  • 1
  • 2

运行client端:

$ python PythonClient.py
ping()
say hello from 10.27.73.176
say world from 10.27.73.176
  • 1
  • 2
  • 3
  • 4

server端输出:

ping()
sayHello()
sayMsg(world)
  • 1
  • 2
  • 3

0x04 使用thriftpy

thriftpy(现已更新为thriftpy2)对thrift进行了封装,可以动态解析thrift接口文件。项目地址:https://github.com/Thriftpy/thriftpy2

安装thriftpy2

sudo pip install thriftpy2
  • 1

编写IDL

pingpong.thrift

service PingService {
string ping(),
}
service AargsPingService {
string ping(1:string ping);
}
service Sleep {
oneway void sleep(1: i32 seconds)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

编写代码

server.py

# coding=utf-8
import thriftpy2
from thriftpy2.rpc import make_server
pp_thrift = thriftpy2.load("pingpong.thrift", module_name="pp_thrift") # 实现.thrift文件定义的接口
class Dispatcher(object):
def ping(self):
print("ping pong!")
return 'pong' def main():
# 定义监听的端口和服务
server = make_server(pp_thrift.PingService, Dispatcher(), '127.0.0.1', 6000)
print("serving...")
server.serve()
if __name__ == '__main__':
main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

client.py

# coding=utf-8
import thriftpy2
#from thriftpy2.rpc import client_context
from thriftpy2.rpc import make_client
# 读入thrift文件,module_name最好与server端保持一致,也可以不保持一致
pp_thrift = thriftpy2.load("pingpong.thrift", module_name="pp_thrift") def main():
#with client_context(pp_thrift.PingService, '127.0.0.1', 6000) as c:
# pong = c.ping()
# print(pong)
client = make_client(pp_thrift.PingService, '127.0.0.1', 6000)
print(client.ping())
if __name__ == '__main__':
main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注释里是另一种创建链接的方式。

目录结构:

├── client.py
├── pingpong.thrift
└── server.py
  • 1
  • 2
  • 3

运行

运行server端:

$ python server.py
serving...
  • 1
  • 2

运行client端:

$ python client.py
pong
  • 1
  • 2

server端输出:

ping pong!

Python使用Thrift的更多相关文章

  1. python Hbase Thrift pycharm 及引入包

    cp -r hbase/ /usr/lib/python2.7/site-packages/ 官方示例子http://code.google.com/p/hbase-thrift/source/bro ...

  2. Golang&Python测试thrift

    接上篇,安装好之后,就开始编写IDL生成然后测试. 一.生成运行 参考 http://www.aboutyun.com/thread-8916-1-1.html 来个添加,查询. namespace ...

  3. Python实现Thrift Server

    近期在项目中存在跨编程语言协作的需求,使用到了Thrift.本文将记录用python实现Thrift服务端的方法. 环境准备 根据自身实际情况下载对应的Thrift编译器,比如我在Windows系统上 ...

  4. 【原创】用python连接thrift Server 去执行sql的问题总汇

    场景:python和现有产品的结合和应用——python的前瞻性调研 环境:centos7 0.首先确保安装了python和pyhive,下面是连接代码: #!/usr/bin/env python ...

  5. python 使用 thrift 教程

    一.前言: Thrift 是一种接口描述语言和二进制通信协议.以前也没接触过,最近有个项目需要建立自动化测试,这个项目之间的微服务都是通过 Thrift 进行通信的,然后写自动化脚本之前研究了一下. ...

  6. 【hbase】使用thrift with python 访问HBase

    HBase 版本: 0.98.6 thrift   版本: 0.9.0 使用 thrift client with python 连接 HBase 报错: Traceback (most recent ...

  7. thrift例子:python客户端/java服务端

    java服务端的代码请看上文. 1.说明: 这两篇文章其实解决的问题是,当使用python去访问大数据线上集群的时候,遇到两个问题: 1)python-hadoop和python-hive相关包链接不 ...

  8. thrift安装及python和c++版本调试

    一.安装过程 1.安装依赖库 ]# yum install boost-devel-static libboost-dev libboost-test-dev libboost-program-opt ...

  9. Python Thrift 简单示例

    本文基于Thrift-0.10,使用Python实现服务器端,使用Java实现客户端,演示了Thrift RPC调用示例.Java客户端提供两个字符串参数,Python服务器端计算这两个字符串的相似度 ...

随机推荐

  1. 关于微信订阅号里自动回复里的a链接的问题

    前阵子做了一个微信订阅号的活动,然后发现一个问题:就是回复内容里的a标签微信没有解析出来,而是这样 正常应该是这样: 具体出现这种情况的手机有: 魅族的型号是:M1 metal小米的型号是:MI 5X ...

  2. C/C++ 交换两个数,不使用第三个变量, 函数模板来实现

    #include <iostream> template<typename T> void exchangeTwoNumber(T &t1, T &t2): v ...

  3. [技术博客] 微信小程序的formid获取

    微信小程序的formid获取 formId的触发 微信小程序可以通过收集用户的formid,获取formid给用户主动推送微信消息.获取formid有两个途径,一个是触发一次表单提交,或者触发一次支付 ...

  4. Shell脚本之一 Shell脚本简介

    一.什么是shell? 我们平时所说的 Shell 可以理解为 Linux 系统提供给用户的使用界面.Shell 为用户提供了输入命令和参数并可得到命令执行结果的环境.当一个用户登录 Linux 之后 ...

  5. ES集群7.3.0设置快照,存储库进行索引备份和恢复等

    说明:三台ES节点组成ES集群,一台kibana主机,版本均是7.3.0,白金试用版 官方地址:https://www.elastic.co/guide/en/elasticsearch/refere ...

  6. asp.net core web的导入导出excel功能

    这里主要记录下asp.net core web页面上进行导入导出excel的操作. 主要是导入,因为现在使用的很多前端框架(例如kendo ui)本身就有导出的功能. 这里使用到EPPlus.Core ...

  7. 两数相加(C#数据结构和算法练习)

    两数相加 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表 ...

  8. .Net调用ffmpeg对视频截图

    2019/10/27, .Net c#代码片段 摘要:借助ffmpeg对视频/图片截图.生成缩略图,使用命令行调用ffmpeg工具,支持Linux和Windows 网上很多版本都是需要等待4s的做法, ...

  9. Web API 授权筛选器

    方式一.全局认证 public static class WebApiConfig { public static void Register(HttpConfiguration config) { ...

  10. C# Linq 使用总结

    隐式类型匿名类型自动属性初始化器委托泛型泛型委托匿名方法Lambda表达式扩展方法迭代器LINQ System.Linq var arr = new[] { "c", " ...