It's Easy to Build RPC Server in Python

I

RPC stands for Remote Procedure Call. RPC server is similar to any HTTP server running on a specific port. RPC also communicates over HTTP but uses XML for data transfer. So, Let’s get started to build it using Python Twisted framework. If you want to know more about RPC, check its Wikipedia page.

Install Python Twsited

I always keep my Python projects inside virtual environments. So, I create a virtual environment using virtualenv Python package and install Python Twisted framework into the virtual environment.

Create an RPC Server

Python Twisted.Web package provides XMLRPC class. We will extend our call from base XMLRPC class.

We are running our RPC server on port 7080. The RPC server exposes three methods, info, add and multiply. The RPC methods have to start with xmlrpc_ key. The other parts of the code, like, endpoint, server, site and reactor are Twisted library components. Start with reactor documentation.

Create RPC client

Let’s build a client to talk to the server and call info, add and multiply methods. Below is the code snippet for the client.

When calling RPC methods, you don’t need to use xmlrpc_ key. You can call them directly as mentioned in the above code.

Conclusion

You may be wondering why I need to create RPC server and Client for simple methods like add and multiply. This is a sample code to demonstrate how to build RPC server/client with Python Twisted. The main use of this RPC server comes when you want to communicate to other machines via Twisted. for example, I want to connect to a remote server via ssh and send commands to that server. Twisted is completely asynchronous and runs its own event loop when we call reactor.run. Read more about this here. It’s really awesome.

comments powered by Disqus

I am Saisyam

I am passionate software developer. I love exploring new technologies and programming languages. Other than coding I love cooking, travelling and photography.

Get in touch

Talk to me about anything related to programming and technology. Happy to help.