不积跬步,无以至千里;不积小流,无以成江海。

Dean's blog

  • Join Us on Facebook!
  • Follow Us on Twitter!
  • LinkedIn
  • Subcribe to Our RSS Feed

Python gRPC小白使用示例

环境配置

安装gRPC

pip install grpcio

安装ProtoBuf依赖库:

pip install protobuf

安装Python gRPC 的ProtoBuf 编译工具:

pip install grpcio-tools

注:在安装grpcio-tools的时候,pip提示了个错误:

ERROR: Could not find a version that satisfies the requirement grpcio-tools (from versions: none)
ERROR: No matching distribution found for grpcio-tools

后来问度娘后,升级pip就解决了:

python -m pip install -U pip

生成文件

1、编写proto文件:

添加example目录并添加data.proto,proto文件是定义的消息,内容:

syntax = "proto3";
package example;
service FormatData {
  rpc DoFormat(Data) returns (Data){}
}
message Data {
  string text = 1;
}

2、生成Python文件:

使用cmd进入example目录,并执行如下语句:

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=../data.proto 

最后example目录文件清单如下:

│ data.proto
│ data_pb2.py
│ data_pb2_grpc.py

添加文件

1、添加server(main.py):

import grpc
import time
from concurrent import futures
import sys
sys.path.append('..')
#sys.path
 
from example import data_pb2, data_pb2_grpc
 
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = 'localhost'
_PORT = '8080'
 
class FormatData(data_pb2_grpc.FormatDataServicer):
    def DoFormat(self, request, context):
        str = request.text
        return data_pb2.Data(text=str.upper())
 
def serve():
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    data_pb2_grpc.add_FormatDataServicer_to_server(FormatData(), grpcServer)
    grpcServer.add_insecure_port(_HOST + ':' + _PORT)
    grpcServer.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        grpcServer.stop(0)
 
if __name__ == '__main__':
    serve()

2、添加client(main.py):

import grpc
import sys
import sys
sys.path.append('..')
 
from example import data_pb2, data_pb2_grpc

 
_HOST = 'localhost'
_PORT = '8080'
 
def run():
    conn = grpc.insecure_channel(_HOST + ':' + _PORT)
    client = data_pb2_grpc.FormatDataStub(channel=conn)
    response = client.DoFormat(data_pb2.Data(text='hello,world!'))
    print("received: " + response.text)
 
if __name__ == '__main__':
    run()

最后项目目录结构:

测试

依次运行server/client,即可看到效果

 

相关链接

Protobuf之proto文件编写规则: https://blog.csdn.net/jiaweiok123/article/details/87809831

gRPC中文文档:http://doc.oschina.net/grpc?t=60138

不允许评论
粤ICP备17049187号-1