ThriftPy2

0.6.0 · active · verified Thu Apr 09

ThriftPy2 is a pure Python implementation of the Apache Thrift protocol, version 0.6.0. It allows developers to parse Thrift IDL files and create RPC clients/servers dynamically without code generation or compilation. The library maintains an active development status with regular updates, including recent beta releases leading to stable versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to dynamically load a Thrift IDL file and instantiate an asynchronous client using `thriftpy2.rpc.make_aio_client`. It creates a temporary `pingpong.thrift` file, loads it, and attempts to connect to a local server. Note that for a successful RPC call, a ThriftPy2 server must be running at the specified address and port.

import asyncio
import thriftpy2
from thriftpy2.rpc import make_aio_client
import os

# Define a simple Thrift service IDL in a temporary file
THRIFT_FILE_PATH = "pingpong.thrift"
with open(THRIFT_FILE_PATH, "w") as f:
    f.write("service PingPong {\n    string ping(),\n}")

# Load the thrift file dynamically
pingpong_thrift = thriftpy2.load(THRIFT_FILE_PATH, module_name="pingpong_thrift")

async def main():
    print("Attempting to create ThriftPy2 async client...")
    client = None
    try:
        # For this quickstart, we'll demonstrate client instantiation and a call pattern.
        # Note: This client will attempt to connect to '127.0.0.1:6000'.
        # A running ThriftPy2 server on this address would be required for a successful RPC call.
        # This example focuses on demonstrating the client API, not a full RPC pair.
        client = await make_aio_client(
            pingpong_thrift.PingPong,
            '127.0.0.1',
            6000,
            timeout=1000 # Milliseconds for connection/read timeout
        )
        print("Client created. Attempting to call ping()... (This will likely fail without a running server)")
        # Example of calling a service method
        # result = await client.ping()
        # print(f"Ping result: {result}")

    except Exception as e:
        print(f"Error setting up client (expected if no server is running at 127.0.0.1:6000): {e}")
    finally:
        if client:
            client.close()
        # Clean up the dummy thrift file
        if os.path.exists(THRIFT_FILE_PATH):
            os.remove(THRIFT_FILE_PATH)

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →