美文网首页
2021-02-26 Python GRPC

2021-02-26 Python GRPC

作者: YuKalix | 来源:发表于2021-02-26 10:31 被阅读0次

参考文档

https://developers.google.com/protocol-buffers/docs/reference/python-generated

安装

pip install grpcio grpcio-tools protobuf

定义Protocol Buffer文件

syntax="proto3";

package test;

service Bi {
    rpc HelloDewei(HelloDeweiReq) returns (HelloDeweiReply) {}
}


message HelloDeweiReq {
    string name = 1;
    int32 age = 2;
}

message HelloDeweiReply {
    string result = 1;
}

生成

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. hello.proto

编写服务端

import grpc
import time
import hello_pb2 as pb2
import hello_pb2_grpc as pb2_grpc

from concurrent import futures


class Bi(pb2_grpc.BiServicer):
    def HelloDewei(self, request, context):
        name = request.name
        age = request.age

        result = f'my name is {name}, i am {age} years old'
        return  pb2.HelloDeweiReply(result=result)


def run():
    mygrpc_server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=4)
    )

    pb2_grpc.add_BiServicer_to_server(Bi(), mygrpc_server)
    mygrpc_server.add_insecure_port('127.0.0.1:9999')
    print('server will start as 127.0.0.1:9999')
    mygrpc_server.start()

    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        mygrpc_server.stop(0)


if __name__ == '__main__':
    run()

编写客户端

import grpc
import hello_pb2 as pb2
import hello_pb2_grpc as pb2_grpc


def run():
    conn = grpc.insecure_channel("127.0.0.1:9999")
    client = pb2_grpc.BiStub(channel=conn)
    response = client.HelloDewei(pb2.HelloDeweiReq(
        name="dewei",
        age=33
    ))

    print(response.result)

if __name__ == '__main__':
    run()

相关文章

  • 2021-02-26 Python GRPC

    参考文档 https://developers.google.com/protocol-buffers/docs/...

  • gRPC之python

    安装 安装grpc 安装python grpc的protobuf的编译工具 安装protobuf的python依赖...

  • gRPC

    基础:GRPC的产生动机和设计原则grpc| python 实战 grpcPython版gRPC入门实验 - 知乎...

  • grpc| python 实战 grpc

    date: 2018-5-15 22:12:32title: grpc| python 实战 grpcdescri...

  • gRPC in Python

    gRPC 是 Google 开放的一款 RPC (Remote Procedure Call) 框架,建立在 HT...

  • python gRPC

    最近在用 python 写项目,项目中有许多 AI 服务需要相互调用,为了服务之间的解耦合,想尝试采用 gRPC ...

  • Java与Python使用grpc跨平台调用

    本文通过grpc实现java与java之间的通信、java和python之间的相互调用、python与python...

  • gRPC 跨进程使用引发的问题

    问题描述 在 Python 项目中使用 gRPC 进行通信,跨进程使用时,会出现阻塞或报错的情况(根据 gRPC....

  • 2021-02-26

    2021-02-26

  • 2021-02-26

    2021-02-26

网友评论

      本文标题:2021-02-26 Python GRPC

      本文链接:https://www.haomeiwen.com/subject/jkcmfltx.html