Thrift Client in Python: Hello World Sample
As mentioned in my last post, Thrift is a cross-language and cross platform RPC framework. We’ve seen how a Java based Thrift server and client work there. Let’s take a look how to write a quick python script that connects to the Java Thrift server. It’s all possibe to write a Python based Thrift server, but probably not what most people want to do due to performance and scalability.
First of all, you want to download the latest (version 0.9.1 as of this writing) Thrift Python package from Python Web site: https://pypi.python.org/pypi/thrift/0.9.1. Once the thrift-0.9.1.tar.gz file is downloaded, unzip it into a local directory. In my case, I just unzip it into C:\temp\thrift-0.9.1. From the directory, run the command to install the thrift client as follows:
Time to learn how to "Google" and manage your VMware and clouds in a fast and secureHTML5 App
C:\temp\thrift-0.9.1>\Dev\Python27\python.exe setup.py install
where \Dev\Python27\python.exe is the full path to my Python runtime. You should change it to your own path.
If the installation is successfully, you should see a new egg file in the site-packages directory as follows: (Again, yours could be different with Python home directory).
Now, let’s find the hello.thrift file (see last post for source) and run the following command:
c:\Dev\thrift-0.9.1>thrift-0.9.1 –gen py hello.thrift
It would generate code into a directory called “gen-py”. Just copy the gen-py to where you will going to create your own Python code. Together with the Thrift library and the generated stub, we’re going to write a simple Python code to call the hi() method.
__author__ = 'Steve Jin' import sys sys.path.append('./gen-py') from hello import Hello from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: print "starting thrift client..." transport = TSocket.TSocket('127.0.0.1', 7911) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hello.Client(protocol) transport.open() print client.hi() transport.close() except Thrift.TException, tx: print str(tx)
It would output
starting thrift client... Hello DoubleCloud.org
With this simple Python script, you probably don’t need an IDE. If you do like to use an IDE, my recommendation is PyCharm from Jetbrain. The intelligent auto completion just makes life so much easier than otherwise.