Wednesday, August 31, 2011

Running the Thrift Tutorial with Python

See the previous post about installing thrift.


We will assume that you are currently in the thrift directory.
The tutorial.thrift file is written very well with lots of useful comments, but here are the few lines of code in this file which we really need:

namespace cpp tutorial
namespace java tutorial
namespace php tutorial
namespace perl tutorial

enum Operation {
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4
}
struct Work {
  1: i32 num1 = 0,
  2: i32 num2,
  3: Operation op,
  4: optional string comment,
}


exception InvalidOperation {
  1: i32 what,
  2: string why
}

service Calculator extends shared.SharedService {

   void ping(),
   i32 add(1:i32 num1, 2:i32 num2),
   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),
   oneway void zip()

}
 
 
Copy the files tutorial.thrift and shared.thrift into a new directory 
Generate the python files
thrift -r --gen py:new_style tutorial.thrift
 
where
-r makes thrift generate included files
--gen py:new_style makes thrift use the py generator with the optional argument of new_style to generate new style classes
 
 
Looking at gen-py/tutorial/Calculator.py you can see that the Calculator Service has been turned into an interface (class Iface).
 
The Iface class is inherited by class Client and class Processor
 
The Client implements the methods defined by the interface.
e.g. the add method does 2 things, calls send_add and returns recv_add.
 
The send_add method will write the name of the method 'add' and its arguments to the Thrift transport.
The recv_add method will receive the result of the add method.
 
In addition to the Client, there is a class called Processor who also implements Iface.
In the case of the add method, the Processor will read the arguments, call the handler who does the add operation and writes the result.
The handler is the important part as this is that class which you will write which implements the methods.



No comments: