博客
关于我
python gRPC简单示例
阅读量:804 次
发布时间:2023-03-05

本文共 3486 字,大约阅读时间需要 11 分钟。

Ubuntu 18.04 安装 gRPC 及示例工程

安装 gRPC

在 Ubuntu 18.04 系统上安装 gRPC 和 Protobuf 可能需要以下步骤:

  • 安装 Protobuf 编译器 gRPC
  • 安装 Protobuf 编译器
  • 使用 pip 安装 gRPC Python 库
  • 安装 Protobuf Python 依赖库
  • 安装 gRPC 的 Python 编译工具
  • 安装完成后,可以开始编写 gRPC 服务和客户端代码。

    编写示例工程

    项目结构

    创建一个新的项目目录,按照以下结构组织代码:

    .├── stream/│   ├── stream.proto│   ├── stream_pb2.py│   └── stream_pb2_grpc.py├── simple_server.py└── simple_client.py

    编写 Protobuf 文件

    stream 目录中创建 stream.proto 文件:

    syntax = "proto3";package stream;service StreamService {  rpc SimpleFun(RequestData) returns (ResponseData) {  }}message RequestData {  string text = 1;}message ResponseData {  string text = 1;}

    使用 Protobuf 生成代码

    stream 目录中执行以下命令,生成 Python 代码:

    python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. stream.proto

    注意:生成的 stream_pb2_grpc.py 文件中,stream__pb2 引用路径需要修正。

    服务器端代码

    编写 simple_server.py

    #! /usr/bin/env python# -*- coding: utf-8 -*-import grpcimport timefrom concurrent import futuresfrom stream import stream_pb2, stream_pb2_grpcONE_DAY_IN_SECONDS = 60 * 60 * 24HOST = 'localhost'_PORT = '8883'class Servicer(stream_pb2_grpc.StreamServiceServicer):    def SimpleFun(self, request, context):        print("received: " + request.text)        return stream_pb2.ResponseData(text='hello,gRPC')def serve():    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))    stream_pb2_grpc.add_StreamServiceServicer_to_server(Servicer(), 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()

    客户端代码

    编写 simple_client.py

    #! /usr/bin/env python# -*- coding: utf-8 -*-import grpcfrom stream import stream_pb2, stream_pb2_grpcHOST = 'localhost'_PORT = '8883'def run():    with grpc.insecure_channel(HOST + ':' + _PORT) as conn:        client = stream_pb2_grpc.StreamServiceStub(channel=conn)        response = client.SimpleFun(stream_pb2.RequestData(text='hello,world!'))        print("received: " + response.text)if __name__ == '__main__':    run()

    运行结果

  • 在终端启动服务器:
  • python simple_server.py
    1. 在另一终端启动客户端:
    2. python simple_client.py

      预计看到如下输出:

      received: hello,world!received: hello,gRPC

      完整代码

      # simple_server.py#! /usr/bin/env python# -*- coding: utf-8 -*-import grpcimport timefrom concurrent import futuresfrom stream import stream_pb2, stream_pb2_grpcONE_DAY_IN_SECONDS = 60 * 60 * 24HOST = 'localhost'_PORT = '8883'class Servicer(stream_pb2_grpc.StreamServiceServicer):    def SimpleFun(self, request, context):        str = request.text        print("received: " + str)        return stream_pb2.ResponseData(text=('hello,gRPC'))def serve():    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4))    stream_pb2_grpc.add_StreamServiceServicer_to_server(servicer(), 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()# simple_client.py#! /usr/bin/env python# -*- coding: utf-8 -*-import grpcfrom stream import stream_pb2, stream_pb2_grpc_HOST = 'localhost'_PORT = '8883'def run():    conn = grpc.insecure_channel(_HOST + ':' + _PORT)    client = stream_pb2_grpc.StreamServiceStub(channel=conn)    response = client.SimpleFun(stream_pb2.RequestData(text='hello,world!'))    print("received: " + response.text)if __name__ == '__main__':    run()

    转载地址:http://exafk.baihongyu.com/

    你可能感兴趣的文章
    python | 高效使用Python工具自动生成模块文档的秘诀
    查看>>
    python 一个list去除另一个list中的值
    查看>>
    python 三大框架的 介绍。
    查看>>
    Python 下载的 11 种姿势,一种比一种高级!
    查看>>
    python读取一个文件夹下所有图片_初学Python-找出文件夹下的所有图片
    查看>>
    Python 中 3 个不可思议的返回功能
    查看>>
    python 中 dict 的另一种用法
    查看>>
    Python 中 PIL 读取图片出现异常旋转的解决方法
    查看>>
    python 中os.path.join 双斜杠的解决办法
    查看>>
    Python 中Semaphore 信号量对象、Event事件、Condition
    查看>>
    python 中with的使用及样例
    查看>>
    Python 中内置的最大堆 API
    查看>>
    Python 中只有一个 True 和一个 False 对象吗?
    查看>>
    python读取mtcars数据集并实现以下操作_关于数据处理。。,Python交流,技术交流区,鱼C论坛 - Powered by Discuz!...
    查看>>
    Python 中多线程与多处理之间的区别
    查看>>
    Python 中如何使用 lambda 函数
    查看>>
    Python 中如何创建多行字符串?
    查看>>
    Python 中如何处理异常?
    查看>>
    Python 中如何实现列表的切片?
    查看>>
    Python 中如何实现字典的排序?
    查看>>