如何用Python搭建gRPC服务

作者:华为云开发者社区 时间:2023-02-08 16:00:54 

一、概述

一个gRPC服务的大体结构图为:

如何用Python搭建gRPC服务

图一表明,grpc的服务是跨语言的,但需要遵循相同的协议(proto)。相比于REST服务,gPRC 的一个很明显的优势是它使用了二进制编码,所以它比 JSON/HTTP 更快,且有清晰的接口规范以及支持流式传输,但它的实现相比rest服务要稍微要复杂一些,下面简单介绍搭建gRPC服务的步骤。

二、安装python需要的库

pip install grpcio

pip install grpcio-tools  

pip install protobuf

三、定义gRPC的接口

创建 gRPC 服务的第一步是在.proto 文件中定义好接口,proto是一个协议文件,客户端和服务器的通信接口正是通过proto文件协定的,可以根据不同语言生成对应语言的代码文件。这个协议文件主要就是定义好服务(service)接口,以及请求参数和相应结果的数据结构,下面是一个简单的例子。


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;
};

四、使用 protoc 和相应的插件编译生成对应语言的代码

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

利用编译工具把proto文件转化成py文件,直接在当前文件目录下运行上述代码即可。

1.-I 指定proto所在目录

2.-m 指定通过protoc生成py文件

3.--python_out指定生成py文件的输出路径

4.hello.proto 输入的proto文件

执行上述命令后,生成hello_pb2.py 和hello_pb2_grpc.py这两个文件。

五、编写grpc的服务端代码


#! /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()

在服务端侧,需要实现hello的方法来满足proto文件中GrpcService的接口需求,hello方法的传入参数,是在proto文件中定义的HelloRequest,context是保留字段,不用管,返回参数则是在proto中定义的HelloResponse,服务启动的代码是标准的,可以根据需求修改提供服务的ip地址以及端口号。

六、编写gRPC客户端的代码


#! /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()

客户端侧代码的实现比较简单,首先定义好访问ip和端口号,然后定义好HelloRequest数据结构,远程调用hello即可。需要强调的是,客户端和服务端一定要import相同proto文件编译生成的hello_pb2_grpc, hello_pb2模块,即使服务端和客户端使用的语言不一样,这也是grpc接口规范一致的体现。

七、调用测试

先启动运行服务端的代码,再启动运行客户端的代码即可。

八、gRPC的使用总结

  • 定义好接口文档

  • 工具生成服务端/客户端代码

  • 服务端补充业务代码

  • 客户端建立 gRPC 连接后,使用自动生成的代码调用函数

  • 编译、运行

来源:https://www.cnblogs.com/huaweiyun/p/14948951.html

标签:Python,gRPC
0
投稿

猜你喜欢

  • Python下载网络文本数据到本地内存的四种实现方法示例

    2022-10-09 15:48:25
  • pytorch索引查找 index_select的例子

    2023-09-12 20:45:05
  • 自适应内容高度的收缩与展开

    2007-09-24 14:38:00
  • 全透视:CSS Z-index 属性

    2009-09-21 12:52:00
  • Python中json库的操作指南

    2021-10-11 11:04:43
  • SQLServer 连接 EXCEL

    2009-07-09 19:00:00
  • Python面向对象实现一个对象调用另一个对象操作示例

    2023-08-30 22:54:35
  • Python中关键字is与==的区别简述

    2022-07-09 10:32:09
  • Python入门之后再看点什么好?

    2023-07-17 07:04:29
  • python 利用 PIL 将数组值转成图片的实现

    2021-03-28 07:17:13
  • Python自然语言处理 NLTK 库用法入门教程【经典】

    2022-10-06 04:36:54
  • python获取百度热榜链接的实例方法

    2022-10-02 23:10:01
  • Python中requests库的用法详解

    2022-04-12 07:05:16
  • Python Excel处理库openpyxl详解

    2021-10-18 13:59:04
  • python查看模块,对象的函数方法

    2021-07-11 19:45:10
  • Django表单提交后实现获取相同name的不同value值

    2023-08-11 01:59:31
  • Sql Server 查询性能优化之走出索引的误区分析

    2012-05-22 18:56:52
  • python对数组进行反转的方法

    2023-08-12 13:38:54
  • python中Requests发送json格式的post请求方法

    2021-05-24 10:09:45
  • CSS网页布局开发时的常见问题小结

    2009-08-13 12:17:00
  • asp之家 网络编程 m.aspxhome.com