本篇文章思路来源官方文档的quickstart, 英文好的朋友可以看官方的原文。

 

安装环境

这里用的python版本为3.6.8,grpc版本为v1.18.0

1升级pip

保证pip的版本为9.0.1或者更高

python -m pip install --upgrade pip

2安装gRPC

# 安装gRPC本身
python -m pip install grpcio
# 安装gRPC相关工具
python -m pip install grpcio-tools

3下载源码

# Clone the repository to get the example code:
git clone -b v1.18.0 https://github.com/grpc/grpc
# Navigate to the "hello, world" Python example:
cd grpc/examples/python/helloworld

4运行gRPC应用

  1. 运行服务端

     

    python greeter_server.py

    另一个窗口的同样目录下,运行客户端

    python greeter_client.py

     

更新gRPC服务

目的是让大家从感性上理解怎么修改服务

  1. 编辑文件 examples/protos/helloworld.proto,并做如下修改(在服务中多了SayHelloAgain函数):

    syntax = "proto3";
    
    option java_multiple_files = true;
    option java_package = "io.grpc.examples.helloworld";
    option java_outer_classname = "HelloWorldProto";
    option objc_class_prefix = "HLW";
    
    package helloworld;
    
    // The greeting service definition.
    service Greeter {
      // Sends a greeting
      rpc SayHello (HelloRequest) returns (HelloReply) {}
      rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
    }
    
    // The request message containing the user's name.
    message HelloRequest {
      string name = 1;
    }
    
    // The response message containing the greetings
    message HelloReply {
      string message = 1;
    }
  2. 保存后运行此文件生成gRPC代码--供服务端和客户端运行的代码

    cd examples/python/helloworld
    python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto

    这个动作将重新生成文件
    helloworld_pb2.py - --包含请求和响应类,helloworld_pb2_grpc.py - --包含客户端和服务端类

更新并运行应用

以下操作所在目录:examples/python/helloworld

  1. 更新服务端(greeter_server.py)代码

    class Greeter(helloworld_pb2_grpc.GreeterServicer):
    
      def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
    
      def SayHelloAgain(self, request, context):
        return helloworld_pb2.HelloReply(message='Hello again, %s!' % request.name)
  2. 更新客户端(greeter_client.py)代码

    def run():
        # NOTE(gRPC Python Team): .close() is possible on a channel and should be
        # used in circumstances in which the with statement does not fit the needs
        # of the code.
        with grpc.insecure_channel('localhost:50051') as channel:
            stub = helloworld_pb2_grpc.GreeterStub(channel)
            response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
            response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name='you'))
        print("Greeter client received: " + response.message)
    
  3. 重新运行服务端和客户端

    在一个窗口运行: 

    python greeter_server.py

    在另一个窗口运行:

    python greeter_client.py

     

总结

只是一个对grpc的感性认识。如果要了解更多,可参照官方文档:什么是gRPC 、gRPC基础:python版
或者关注后续博文。