首页 > 解决方案 > 如何将节俭结构传递给 Python 服务器

问题描述

我正在使用 thrift 在 python 服务器和 java 客户端之间进行 rpc 通信。在我的节俭处理程序中,我有一个要传递节俭结构的函数。对于基本数据类型传递,我可以直接做:

def assignValue(self, variable, value):

但现在我想传递结构而不是变量(它是字符串类型)。我怎样才能做到这一点?

struct MyStruct { 1:string var1; 2:string var2; }

PS:我是thrift的新手,我正在关注thrift的官方文档,如果有任何其他文档可以提供帮助,请随时传递。谢谢!

标签: pythonthrift

解决方案


这是一个在 Thrift IDL 中传递结构的简单示例:

https://github.com/RandyAbernethy/ThriftBook/blob/master/part1/arch/halibut.thrift

struct Date {
    1: i16  year
    2: i16  month
    3: i16  day
}

service HalibutTracking {
    i32 get_catch_in_pounds_today()
    i32 get_catch_in_pounds_by_date(1: Date dt, 2: double tm)
}

这里有一个 Java 客户端和服务器示例:

https://github.com/RandyAbernethy/ThriftBook/tree/master/part3/ws/thrift

它显示返回一个结构(但传递一个很容易推断)。在 Python 和 Java 的 ThriftBook 存储库中也有许多示例(所有来源都来自 Programmer's Guide to Apache Thrift):

示例 struct return thrift idl 如下所示:

struct TradeReport {
    1: string  symbol,
    2: double  price,
    3: i32     size,
    4: i32     seq_num
} 

service TradeHistory {
    TradeReport get_last_sale(1: string Symbol) 
}

清单中的 Java 客户端如下所示:

import java.io.IOException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.protocol.TBinaryProtocol;

public class ThriftClient {
    public static void main(String[] args) 
            throws IOException, TException {
        TSocket trans = new TSocket("localhost", 9090);
        TBinaryProtocol proto = new TBinaryProtocol(trans);
        TradeHistory.Client client = new TradeHistory.Client(proto);

        trans.open();
        for (int i = 0; i < 1000000; i++) {
            TradeReport tr = client.get_last_sale("APPL");
        }
        trans.close();
    }
}

其他 IDL 示例在这里(包括几个传递结构的示例):

https://github.com/RandyAbernethy/ThriftBook/tree/master/part2/IDL


推荐阅读