0

我想知道用 ThriftPy 对结构列表进行二进制编码的最佳方法是什么。我发现的唯一方法是创建另一个包装器struct并从流中删除二进制前缀/后缀,但这非常hacky,肯定有更好的方法。

foob​​ar.thrift:

struct Object {
  1: i32 num1 = 0,
  2: i32 num2,
}

struct ListContainer {
    1: list<Object> objects
}

应用程序.py

foobar = thriftpy.load('foobar.thrift', module_name="foobar_thrift")

objects = [ ... list of Objects ... ]

thrift_obj = foobar.ListContainer(objects)

trans = TMemoryBuffer()
thrift_obj.write(TBinaryProtocol(trans))

encoded_list = bytes(trans.getvalue())[3:-1]
4

1 回答 1

0

我找到了一个解决方案......不是特别优雅,但比前一个更好。

foob​​ar.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())

我试图看看标准的节俭实现是做什么的。它并没有让它变得更容易。它不会为ObjectListso 生成任何东西,以便实现您必须做的事情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()
于 2017-01-14T03:01:25.420 回答