Thrift的Python入门示例

在本文中,我们将以一个Python示例来解解如何利用Thrift构建一个服务器并使用客户端进行调用。

环境准备

安装Thrift

创建Thrift文件

如下为一个简单的Thrift文件HelloService.thrift

service HelloService {  
    void sayHello()
    string getData(1:string input)  
}

在该文件中,我们定义了一个HelloService的服务,这个服务中包含了两个接口:

  • sayHello:该函数不需要输入值,也没有返回值
  • getData:该函数有一个字符串作为输入值,同时有一个字符串作为返回值。

编译Thrift文件

当我们编写完成Thrift文件后,可以执行如下代码来编译Thrift文件,从而生成一个Python的项目文件夹。

thrift --gen py HelloService.thrift

执行完成后,我们查看当前文件夹可以发现当前在文件夹下已经有了一个新的文件夹,称为gen-py

标题

编写服务器文件

下面,我们可以在gen-py文件夹下创建一个服务器端的server.py文件,以实现在Thrift文件中定义的接口的功能:

# -*- coding: UTF-8 -*-
"""
# WANGZHE12
"""
from HelloService import HelloService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class HelloServiceHandler:
    """
    # HelloServiceHandler是中定义的方法用于实现在thrift文件中定义的接口
    """
    def __init__(self):
        self.log = {}
    def sayHello(self):
        # sayHello接口的实现
        print('sayHello')
    def getData(self, input):
        # getData接口的实现
        return input+' from server 1024'
# 实例化Handler
handler = HelloServiceHandler()
# 根据handler创建一个processor
processor = HelloService.Processor(handler)
# 指定端口启动transport
transport = TSocket.TServerSocket(port=9090)
# 创建tfactory, pfactory
tfactory = TTransport.TBufferedTransportFactory()  
pfactory = TBinaryProtocol.TBinaryProtocolFactory()  
# 创建Server
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)  
print('Starting the server...')
# 启动server
server.serve()  
print('done.')  

启动服务器

server.py文件编写完成后,我们可以在gen-py文件夹下启动Server服务:

python server.py

 

创建客户端文件

服务器端服务启动后,为了测试服务器端的服务是否能够正常启动,我们需要创建一个客户端调用文件client.py

# -*- coding: UTF-8 -*-
"""
# WANGZHE12
"""
from HelloService import HelloService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
    # 连接Socket
    transport = TSocket.TSocket('localhost', 9090)
    # 获取Transport
    transport = TTransport.TBufferedTransport(transport)
    # 获取TBinaryProtocol
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    # 创建一个Client
    client = HelloService.Client(protocol)
    # 连接通道transport
    transport.open()
    # 调用某个没有返回值的函数
    client.sayHello()
    # 调用某个有返回值的函数
    print(client.getData("client access"))
    # 关闭通道transport
    transport.close()
except Thrift.TException, tx:
    print '%s' % (tx.message)

实验一下吧:

服务器端服务已经正常启动了,同时我们也已经编写好了客户端端的测试文件,下面,我们来运行一下client.py文件测试一下吧:

python client.py

此时,如果一切服务正常的话,在客户端的输出中,我们可以看到打印如下内容:

client access from server 1024

而在服务器端可以看到打印了如下内容:

sayHello

 

 
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Thrift is a framework for building cross-language services. It allows you to define data types and service interfaces in a simple definition file, and then generate code in various languages to implement those interfaces. In Python, you can use the Thrift library to create both client and server applications. To use Thrift in Python, you first need to install the Thrift library. You can do this using pip: ``` pip install thrift ``` Once installed, you can start using Thrift in your Python code. Here's a simple example to get you started: 1. Define your data types and service interface in a Thrift IDL file (e.g., `example.thrift`): ``` namespace py example struct MyStruct { 1: required string name 2: optional i32 age } service MyService { MyStruct getStruct(1: string id) } ``` 2. Generate Python code from the IDL file using the `thrift` compiler: ``` thrift --gen py example.thrift ``` 3. Implement the service interface in Python: ```python from example import MyService, ttypes class MyHandler: def getStruct(self, id): # Implementation code goes here return ttypes.MyStruct(name="John", age=25) handler = MyHandler() processor = MyService.Processor(handler) # Run the server transport = TSocket.TServerSocket(port=9090) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) server.serve() ``` 4. Create a client to interact with the server: ```python from example import MyService, ttypes transport = TSocket.TSocket("localhost", 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = MyService.Client(protocol) transport.open() struct = client.getStruct("123") print(struct.name) print(struct.age) transport.close() ``` This is just a basic example to give you an idea of how to use Thrift with Python. You can find more details and advanced usage in the Thrift documentation.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值