2016-12-22 8 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} 

이 같은 직렬화 코드 :

parse_item = Article() 
parse_item.test = 1 

상관없이 str을, INT, BOOL, 또는 더블 :

transport_out = TTransport.TMemoryBuffer() 
protocol_out = TBinaryProtocol.TBinaryProtocol(transport_out) 
parse_item.write(protocol_out) 
bytes = transport_out.getvalue() 

가 parse_item이 기사의 목적은 값을 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"(!)로 변경됩니다. 놀랄만 한, 그러나 현명한 반영에.

직렬화에 적합한 유형을 얻으려면 Generic 인스턴스를 만들고 테스트를 설정해야합니다.

여기에 작업 코드를 통해 산책입니다 :

[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