Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

Thrift Interfacing

Peter Ruibal edited this page Jun 14, 2014 · 1 revision

Let's implement a thrift service with sparts.

Code Generation

Say we have the following thrift/counter.thrift:

service CounterService {
  i64 getCounter(),
  void incrementCounter(),
}

We run the following with bash:

$ thrift -out myproject/gen -v --gen py:new_style thrift/counter.thrift

This will generate the following files:

  • myproject/gen/counter/CounterService.py
  • myproject/gen/counter/ttypes.py
  • myproject/gen/counter/__init__.py
  • myproject/gen/counter/constants.py

With these generated files, you can instantiate servers and clients easily.

Server

There are two parts to a thrift server, the server event handling loop, and the handler itself. sparts abstracts this cleanly with separate tasks.

# Import the generated code
from myproject.gen.counter import CounterService

# Import our server and handler tasks
from sparts.tasks.thrift import NBServerTask, ThriftHandlerTask

# Subclass NBServerTask as necessary to set default port, module, as necessary
class CounterNBServer(NBServerTask):
    DEFAULT_PORT = 9099  # Only required if you don't want to pass --thrift-port
    MODULE = CounterService  # Only required if you're running multiple servers

CounterNBServer.register()

# Implement the thrift handler
class CounterHandler(ThriftHandlerTask):
    MODULE = CounterService
    counter = 0

    def incrementCounter(self):
        self.counter += 1

    def getCounter(self):
        return self.counter

CounterHandler.register()

from sparts.vservice import VService
VService.initFromCLI()

Client

sparts provides a thrift client wrapper to make it easier to work with thrift clients. It supports lazy connection (not connecting to the service until the first call is made), and will have more helpful features (e.g., auto-reconnection) later.

This is how you use it:

# Import the generated code
from myproject.gen.counter import CounterService

# Import the Thrift client helper
from sparts.thrift.client import ThriftClient

# Make the thrift client
client = ThriftClient(host='127.0.0.1', port=9099, module=CounterService)

# Use it!
client.incrementCounter()
print client.getCounter()
Clone this wiki locally