How to call RPC interface in Python is a problem that many Python developers are concerned about. In this article, the good programmer Python training editor will share the detailed explanation of RPC interface call in Python. There are detailed codes listed in the article. Like small partners with small make up together to take a look, I hope to help you.

The python packages to be installed are as follows:

1. GRPC installation

pip install grpcio

GRPC python Protobuf compilation tools

pip install grpcio-tools

3. Protobuf related Python dependency libraries

pip install protobuf

4. A collection of common prototype generated Python classes:

pip install googleapis-common-protos

Compiling protobuf files: Generate Python code using the following command:

Python3 -m grpc_tools.protoc -i < target directory > –python_out=. –grpc_python_out=< target directory path > < target file data.proto>

python3 -m grpc_tools.protoc -I. –python_out=. –grpc_python_out=. data.proto

Note: the protobuf file, which defines the service interface code file, is data.proto

Py and data_PB2_grpc.py are generated

Data_pb2.py is a service interface mapping

Data_pb2_grpc. py method mapping

Examples of protobuf content:

syntax = “proto3”;

package grpcDemo;

message HelloRequest {

string name = 1;

}

message HelloReply {

string message = 1;

}

service gRPC {

rpc SayHello (HelloRequest) returns (HelloReply) {}

}

Example of interface call content:

# -*- coding: utf-8 -*-

import grpc

import data_pb2,data_pb2_grpc

_HOST = ‘localhost’

_PORT = ‘8080’

def run():

conn = grpc.insecure_channel(_HOST + ‘:’ + _PORT)

client = data_pb2_grpc.gRPCStub(channel=conn)

response = client.SayHello(data_pb2.HelloRequest(name=’hello,world! ‘))

print(“received: ” + response.text)

if __name__ == ‘__main__’:

run()