Skip to content

Instantly share code, notes, and snippets.

@jerinisready
Created June 4, 2023 12:46
Show Gist options
  • Save jerinisready/45a0fc15432187f16db6f39241197db8 to your computer and use it in GitHub Desktop.
Save jerinisready/45a0fc15432187f16db6f39241197db8 to your computer and use it in GitHub Desktop.
Demonstration and code reference for RPC in Python Demo for youtube shorts ( https://youtube.com/shorts/fBjxXnTES40 )

RPC in Python Demo

Simplest minimum code for demo - https://youtube.com/shorts/fBjxXnTES40 RPC in Python Concept

Here is the example of 2 implementations:

  • XMLRPC
  • JSONRPC

I am using python examples here; Do not misunderstand this. RPC's are available in every language. Just serarch for it in your favorite language

While xmlrpc is a builtin module to python, we have to install jsonrpc using pip install jsonrpc

XML RPC Implementation in Python

Here's a simple example of Remote Procedure Call (RPC) using Python's xmlrpc module:

Server-side code (server.py):

from xmlrpc.server import SimpleXMLRPCServer

def add_numbers(x, y):
    return x + y

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(add_numbers, "add_numbers")

print("Server listening on port 8000...")
server.serve_forever()

Client-side code (client.py):

import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
result = proxy.add_numbers(4, 5)
print("Result:", result)

To run this code, follow these steps:

  1. Start the server by running python server.py in one terminal.
  2. In another terminal, run python client.py. The client will connect to the server and call the add_numbers method with arguments 4 and 5.
  3. The server will receive the RPC call, execute the add_numbers function, and return the result.
  4. The client will print the result received from the server.

This is a basic demonstration of RPC in Python using XML-RPC. You can extend this example by adding more functions and implementing additional functionality as needed.


JSON RPC Implementation

Here's a simple example of JSON-RPC using the jsonrpcclient library in Python:

Installing Json-RPC

pip install json-rpc

Server-side code (server.py):

from jsonrpcserver import method, serve

@method
def add_numbers(x, y):
    return x + y

serve()

Client-side code (client.py):

from jsonrpcclient import request

response = request("http://localhost:5000", "add_numbers", x=4, y=5)
result = response.json()['result']
print("Result:", result)

To run this code, follow these steps:

  1. Start the server by running python server.py in one terminal. The server will start listening on port 5000.
  2. In another terminal, run python client.py. The client will send a JSON-RPC request to the server, calling the add_numbers method with arguments 4 and 5.
  3. The server will receive the JSON-RPC request, execute the add_numbers method, and return the result.
  4. The client will print the result received from the server.

This is a basic demonstration of JSON-RPC in Python using the jsonrpcclient library. You can extend this example by adding more methods and implementing additional functionality as needed.


The following is a bit advanced topic.

gRPC Implementation [Optional]

gRPC is a modern open source high performance Remote Procedure Call (RPC) framework that can run in any environment by Google. gRPC Seems to be a bit Complicated for beginners; but trust me, when others handles as string, gRPC handles as binary structure and hence brings a huge advantage of performance over inter process communication.

Refer: gRPC

Simplified thought:

  1. Install gRPC;
  2. Create a standard message structure by following the recommendation by gRPC in its official docs.
  3. Generate the gRPC code for using grpc command in the structure.
  4. Create a server, to pass the data using the generated class.
  5. Create a client, to pass the data using the generated class.

First, you'll need to install the required packages. You can install grpcio and grpcio-tools using pip:

pip install grpcio grpcio-tools

Once you have the packages installed, you'll need to define the gRPC service and generate the code.

  1. Create a file called greeter.proto with the following content:
syntax = "proto3";

package greeter;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}
  1. Generate the gRPC code from the protocol buffer file using the protoc compiler. Run the following command in the terminal:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. greeter.proto

This command generates greeter_pb2.py and greeter_pb2_grpc.py files based on the greeter.proto definition.

  1. Create a server-side file called server.py with the following content:
import grpc
import greeter_pb2
import greeter_pb2_grpc

class Greeter(greeter_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        response = greeter_pb2.HelloResponse()
        response.message = "Hello, " + request.name + "!"
        return response

server = grpc.server(grpc.ThreadPoolExecutor())
greeter_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
  1. Create a client-side file called client.py with the following content:
import grpc
import greeter_pb2
import greeter_pb2_grpc

channel = grpc.insecure_channel("localhost:50051")
stub = greeter_pb2_grpc.GreeterStub(channel)

request = greeter_pb2.HelloRequest()
request.name = "Alice"

response = stub.SayHello(request)

print(response.message)

Now you can run the server and client scripts separately in separate terminals:

python server.py
python client.py

The server will start and listen on port 50051. The client will send a request to the server and receive a response, which will be printed on the client side.


gRPC is available over a lot of languages. check out your interesting from the official docs.

Select a language to get started:


Thank You!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment