• 技术文章 >Python技术 >Python基础教程

    Python如何搭建gRPC服务

    小妮浅浅小妮浅浅2021-09-11 09:28:23原创3218

    1、安装python所需的库。

    1

    2

    3

    pip install grpcio

    pip install grpcio-tools 

    pip install protobuf

    2、定义gRPC接口。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    syntax = "proto3";

    option cc_generic_services = true;

    //定义服务接口

    service GrpcService {

        rpc hello (HelloRequest) returns (HelloResponse) {}  //一个服务中可以定义多个接口,也就是多个函数功能

    }

    //请求的参数

    message HelloRequest {

        string data = 1;   //数字1,2是参数的位置顺序,并不是对参数赋值

        Skill skill = 2;  //支持自定义的数据格式,非常灵活

    };

    //返回的对象

    message HelloResponse {

        string result = 1;

        map<string, int32> map_result = 2; //支持map数据格式,类似dict

    };

    message Skill {

        string name = 1;

    };

    3、用protoc和插件编译生成语言代码。

    1

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

    使用编译工具将proto文件转换成py文件,直接在当前文件目录下运行上述代码。

    4、编写grpc服务器代码。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    #! /usr/bin/env python

    # coding=utf8

    import time

    from concurrent import futures

    import grpc

    from gRPC_example import hello_pb2_grpc, hello_pb2

    _ONE_DAY_IN_SECONDS = 60 * 60 * 24

    class TestService(hello_pb2_grpc.GrpcServiceServicer):

        '''

        继承GrpcServiceServicer,实现hello方法

        '''

        def __init__(self):

            pass

        def hello(self, request, context):

            '''

            具体实现hello的方法,并按照pb的返回对象构造HelloResponse返回

            :param request:

            :param context:

            :return:

            '''

            result = request.data + request.skill.name + " this is gprc test service"

            list_result = {"12": 1232}

            return hello_pb2.HelloResponse(result=str(result),

                                           map_result=list_result)

    def run():

        '''

        模拟服务启动

        :return:

        '''

        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

        hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)

        server.add_insecure_port('[::]:50052')

        server.start()

        print("start service...")

        try:

            while True:

                time.sleep(_ONE_DAY_IN_SECONDS)

        except KeyboardInterrupt:

            server.stop(0)

    if __name__ == '__main__':

        run()

    5、编写gRPC客户端代码。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    #! /usr/bin/env python

    # coding=utf8

    import grpc

    from gRPC_example import #! /usr/bin/env python

    # coding=utf8

    import grpc

    from gRPC_example import hello_pb2_grpc, hello_pb2

    def run():

        '''

        模拟请求服务方法信息

        :return:

        '''

        conn=grpc.insecure_channel('localhost:50052')

        client = hello_pb2_grpc.GrpcServiceStub(channel=conn)

        skill = hello_pb2.Skill(name="engineer")

        request = hello_pb2.HelloRequest(data="xiao gang", skill=skill)

        respnse = client.hello(request)

        print("received:",respnse.result)

    if __name__ == '__main__':

        run()

    def run():

        '''

        模拟请求服务方法信息

        :return:

        '''

        conn=grpc.insecure_channel('localhost:50052')

        client = hello_pb2_grpc.GrpcServiceStub(channel=conn)

        skill = hello_pb2.Skill(name="engineer")

        request = hello_pb2.HelloRequest(data="xiao gang", skill=skill)

        response = client.hello(request)

        print("received:",response.result)

    if __name__ == '__main__':

        run()

    6、调用测试。

    首先启动运行服务器的代码,然后启动运行客户端的代码。

    以上就是Python搭建gRPC服务的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python grpc
    上一篇:python套接字编程的服务器和客户端 下一篇:Python lambda的速写用法

    相关文章推荐

    • python ChainMap标准库的跟踪使用• python ChainMap管理应用程序设置• python类属性的两种分类• python抽象类的使用• python中XML有哪些解析模块的方法• python中XML删除元素• python套接字编程的服务器和客户端

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网