我在topic.thrift文件中定义了一个union类型,并生成了gen-py。 像这样:
union Generic{
1: string s,
2: bool b,
3: i64 i,
4: double d}
struct Article{
1: string title,
2: string content,
3: Generic test}
和序列化代码如下:
transport_out = TTransport.TMemoryBuffer()
protocol_out = TBinaryProtocol.TBinaryProtocol(transport_out)
parse_item.write(protocol_out)
bytes = transport_out.getvalue()
parse_item是Article:
的对象parse_item = Article()
parse_item.test = 1
无论str,int,bool还是分配给parse_item.test的double值,我都会得到这样的错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gen-py/topic/ttypes.py", line 189, in write
self.test.write(oprot)
AttributeError: 'str' object has no attribute 'write'
我真的不知道为什么?有人有想法吗?
答案 0 :(得分:2)
这是一个棘手的问题。问题是Python实现利用了Python的动态类型。通过为parse_item结构分配一个int&#34; test&#34;属性,您将其类型更改为&#34; int&#34; (!)。令人惊讶,但反思合情合理。
要获得正确的序列化类型,您需要创建一个Generic实例并对其进行测试。
以下是工作代码:
root@154eadaaea91:/ThriftBook/test2# cat un.thrift
union Generic{
1: string s,
2: bool b,
3: i64 i,
4: double d}
struct Article{
1: string title,
2: string content,
3: Generic test}
root@154eadaaea91:/ThriftBook/test2# thrift -gen py un.thrift
root@154eadaaea91:/ThriftBook/test2# ll
total 20
drwxr-xr-x 3 root root 4096 Dec 22 20:07 ./
drwxr-xr-x 8 root root 4096 Dec 22 19:53 ../
drwxr-xr-x 3 root root 4096 Dec 22 20:07 gen-py/
-rw-r--r-- 1 root root 133 Dec 22 15:46 un.thrift
-rw-r--r-- 1 root root 589 Dec 22 20:07 untest.py
root@154eadaaea91:/ThriftBook/test2# cat untest.py
import sys
sys.path.append("gen-py")
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from un import ttypes
parse_item = ttypes.Article()
gen = ttypes.Generic()
gen.i = 1
parse_item.test = gen
transport_out = TTransport.TMemoryBuffer()
protocol_out = TBinaryProtocol.TBinaryProtocol(transport_out)
parse_item.write(protocol_out)
bytes = transport_out.getvalue()
transport_in = TTransport.TMemoryBuffer(bytes)
protocol_in = TBinaryProtocol.TBinaryProtocol(transport_in)
dump_item = ttypes.Article()
dump_item.read(protocol_in)
print(dump_item.test.i)
root@154eadaaea91:/ThriftBook/test2# python untest.py
1
root@154eadaaea91:/ThriftBook/test2#