简介:本篇文章将通过一个简单的示例来展示如何使用Python的gRPC库来创建一个基本的gRPC服务器和客户端。我们将实现一个简单的计算器服务,其中服务器能够响应客户端的加法请求。
在开始之前,请确保您已经安装了grpcio和protobuf库。如果尚未安装,可以使用以下命令进行安装:
pip install grpcio protobuf
接下来,我们将创建一个简单的计算器服务。首先,我们需要定义服务定义和消息类型。在calculator.proto文件中,我们将定义服务定义和消息类型:
syntax = "proto3";package calculator;// The calculator service definition.service Calculator {// Obligatory “hello world” example.rpc Add (AddRequest) returns (AddResponse);}// The request message containing two ints.message AddRequest {int32 a = 1;int32 b = 2;}// The response message containing the sum.message AddResponse {int32 sum = 1;}
接下来,我们将使用protoc编译器生成Python代码。运行以下命令生成代码:
python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./ calculator.proto
这将生成两个文件:calculator_pb2.py和calculator_pb2_grpc.py。现在我们可以编写gRPC服务器和客户端代码。
首先,我们来实现gRPC服务器。在server.py文件中,我们将编写以下代码:
import grpcfrom concurrent import futuresimport timefrom calculator_pb2 import AddRequest, AddResponsefrom calculator_pb2_grpc import CalculatorServicer, add_to_serverclass Calculator(CalculatorServicer):def Add(self, request, context):a = request.ab = request.breturn AddResponse(sum=a + b)