TProtocol

TProtocol

  protocol提供抽象的写入与读取的方法。

  

1、消息(Message)的读写。消息就是一个完整的包。name一般是方法名,如get(),则name为"get"。

  

  

  ttype是TMessageTYpe消息类型,指明是调用(call)、还是回复(reply)、或是异常(exception)。

  

2、struct是结构体的抽象。譬如一个get方法的args方法,则其name会被命名为get_args。

  

  

3、一个struct包含多个Field。name是结构体名字,ttype是结构类型,如TType.I32,fid是在struct中的惟一序列号。

  

  

  一个实例:

 1 class get_args:
 2   """
 3   Attributes:
 4    - id
 5   """
 6 
 7   thrift_spec = (
 8     None, # 0
 9     (1, TType.I32, 'id', None, None, ), # 1
10   )
11 
12   def __init__(self, id=None,):
13     self.id = id
14 
15   def read(self, iprot):
16     if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
17       fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
18       return
19     iprot.readStructBegin()
20     while True:
21       (fname, ftype, fid) = iprot.readFieldBegin()
22       if ftype == TType.STOP:
23         break
24       if fid == 1:
25         if ftype == TType.I32:
26           self.id = iprot.readI32();
27         else:
28           iprot.skip(ftype)
29       else:
30         iprot.skip(ftype)
31       iprot.readFieldEnd()
32     iprot.readStructEnd()
33 
34   def write(self, oprot):
35     if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
36       oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
37       return
38     oprot.writeStructBegin('get_args')
39     if self.id is not None:
40       oprot.writeFieldBegin('id', TType.I32, 1)
41       oprot.writeI32(self.id)
42       oprot.writeFieldEnd()
43     oprot.writeFieldStop()
44     oprot.writeStructEnd()
View Code
原文地址:https://www.cnblogs.com/tekka/p/4548452.html