2016-12-22 3 views
2

topic.thriftファイルに共用体型を定義し、gen-pyを生成します。python thrift union型はシリアル化できませんか?

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が条の目的である:

parse_item = Article() 
parse_item.test = 1 

どんなに列str、int型、ブール値、または二本のような parse_item.testに割り当てられた値、私はすべてこのようなエラーを受け取ります:

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' 

私は本当に理由を知らないのですか?誰でもアイデアはありますか?

答えて

2

これはトリッキーなものです。問題は、Pythonの実装がPythonの動的な型付けを利用することです。 parse_item構造体の "test"属性にintを代入すると、その型が "int"(!)に変更されます。驚くべきことに、反射的な感覚で。

シリアル化に適したタイプを取得するには、汎用インスタンスを作成し、それにテストを設定する必要があります。

[email protected]:/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} 

[email protected]:/ThriftBook/test2# thrift -gen py un.thrift 
[email protected]:/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 
[email protected]:/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) 
[email protected]:/ThriftBook/test2# python untest.py 
1 
[email protected]:/ThriftBook/test2# 
+0

ええ、ああ:ここ

は動作するコードとの散歩です!ありがとう!私は、ユニオンの構造は難しいと思う!オプションの多分は代替選択肢を使用してください。 – Nan

関連する問題