我找到了一个解决方案......不是特别优雅,但比前一个更好。
foobar.thrift:
struct Object {
1: i32 num1 = 0,
2: i32 num2,
}
typedef list<Object> ObjectList
应用程序.py:
import thriftpy
from thriftpy.transport import TMemoryBuffer
from thriftpy.protocol.binary import write_val
foobar = thriftpy.load('foobar.thrift')
def write_list(trans, val, list_type):
ttype, spec = list_type
write_val(trans, ttype, val, spec=spec)
val = [foobar.Object(num1=8, num2=12)]
trans = TMemoryBuffer()
write_list(trans, val, foobar.ObjectList)
encoded_list = bytes(trans.getvalue())
我试图看看标准的节俭实现是做什么的。它并没有让它变得更容易。它不会为ObjectList
so 生成任何东西,以便实现您必须做的事情thrift -gen py foobar.thrift
,然后:
应用程序.py:
import sys
sys.path.append('gen-py')
from foobar.ttypes import *
from thrift.protocol import TBinaryProtocol
from thrift.transport import TTransport
def write_list(trans, val):
protocol = TBinaryProtocol.TBinaryProtocol(trans)
protocol.writeListBegin(TType.STRUCT, len(val))
for values in val:
values.write(protocol)
protocol.writeListEnd() # This is a nop
val = [Object(num1=8, num2=12)]
trans = TTransport.TMemoryBuffer()
write_list(trans, val)
encoded_list = trans.getvalue()