经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
跨界协作:借助gRPC实现Python数据分析能力的共享
来源:cnblogs  作者:wang_yb  时间:2024/2/19 9:20:27  对本文有异议

gRPC是一个高性能、开源、通用的远程过程调用(RPC)框架,由Google推出。
它基于HTTP/2协议标准设计开发,默认采用Protocol Buffers数据序列化协议,支持多种开发语言。

在gRPC中,客户端可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用和服务。

gRPC支持多种语言,并提供了丰富的接口和库,以及简单易用的API,方便开发者进行快速开发和部署。
同时,gRPC的底层框架处理了所有强制严格的服务契约、数据序列化、网络通讯、服务认证、访问控制、服务观测等等通常有关联的复杂性,使得开发者可以更加专注于业务逻辑的实现。

1. 为什么用 gRPC

我平时用的最多的语言其实是golang,但是,做数据分析相关的项目,不太可能绕开python那些优秀的库。
于是,就想把数据分析的核心部分用python来实现,并用gRPC接口的方式提供出来。
其他的业务部分,仍然用原先的语言来实现。

gRPC相比于http REST,性能和安全上更加有保障,而且对主流的开发语言都支持的很好,不用担心与其他语言开发的业务系统对接的问题。

最后,gRPC虽然接口的定义和实现比http REST更复杂,但是,它提供了方便的命令行工具,
可以根据protocol buf的定义自动生成对应语言的类型定义,以及stub相关的代码等等。

实际开发时,一般只要关注接口的定义和业务功能的实现即可,gRPC框架需要的代码可以通过命令行工具生成。

2. 安装

对于Python语言,安装gRPC框架本身和对应的命令行工具即可:

  1. $ pip install grpcio # gRPC框架
  2. $ pip install grpcio-tools # gRPC命令行工具

3. 开发步骤

开发一个gPRC接口一般分为4个步骤

  1. 使用[protocal buf](https://protobuf.dev/overview)定义服务接口
  2. 通过命令行生成clientserver的模板代码
  3. 实现server端代码(具体业务功能)
  4. 实现client端代码(具体业务功能)

下面通过一个示例演示gRPC接口的开发步骤。
这个示例来自最近做量化分析时的一个指标(MACD)的实现,
为了简化示例,下面实现MACD指标的业务功能部分是虚拟的,不是实际的计算方法。

3.1. 定义服务接口

接口主要定义方法,参数,返回值。

  1. syntax = "proto3";
  2. package idc;
  3. // 定义服务,也就是对外提供的功能
  4. service Indicator {
  5. rpc GetMACD(MACDRequest) returns (MACDReply) {}
  6. }
  7. // 请求的参数
  8. message MACDRequest {
  9. string start_date = 1; // 交易开始时间
  10. string end_date = 2; // 交易结束时间
  11. }
  12. // 返回值中每个对象的详细内容
  13. message MACDData {
  14. string date = 1; // 交易时间
  15. float open = 2; // 开盘价
  16. float close = 3; // 收盘价
  17. float high = 4; // 最高价
  18. float low = 5; // 最低价
  19. float macd = 6; // macd指标值
  20. }
  21. // 返回的内容,是一个数组
  22. message MACDReply {
  23. repeated MACDData macd = 1;
  24. }

3.2. 生成模板代码

grpc_sample目录下,执行命令:

  1. python -m grpc_tools.protoc -I./protos --python_out=. --pyi_out=. --grpc_python_out=. ./protos/indicator.proto

生成后文件结构如下:
image.png
生成了3个文件:

  1. indicator_pb2.pyproto文件定义的消息类
  2. indicator_pb2_grpc.py:服务端和客户端的模板代码
  3. indicator_pb2.pyi:不是必须的,为了能让mypy等工具校验代码类型是否正确

3.3. server端代码

通过继承indicator_pb2_grpc.py文件中的服务类,实现服务端功能。

  1. # -*- coding: utf-8 -*-
  2. from concurrent import futures
  3. import grpc
  4. import indicator_pb2
  5. import indicator_pb2_grpc
  6. class Indicator(indicator_pb2_grpc.IndicatorServicer):
  7. def GetMACD(self, request, context):
  8. macd = []
  9. for i in range(1, 5):
  10. data = indicator_pb2.MACDData(
  11. date=request.start_date,
  12. open=i * 1.1,
  13. close=i * 2.1,
  14. high=i * 3.1,
  15. low=i * 0.1,
  16. macd=i * 2.5,
  17. )
  18. macd.append(data)
  19. return indicator_pb2.MACDReply(macd=macd)
  20. def serve():
  21. port = "50051"
  22. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  23. indicator_pb2_grpc.add_IndicatorServicer_to_server(Indicator(), server)
  24. server.add_insecure_port("[::]:" + port)
  25. server.start()
  26. print("Server started, listening on " + port)
  27. server.wait_for_termination()
  28. if __name__ == "__main__":
  29. serve()

服务端需要实现proto文件中定义接口的具体业务功能。

3.4. client端代码

使用indicator_pb2_grpc.py文件中的Stub来调用服务端的代码。

  1. # -*- coding: utf-8 -*-
  2. import grpc
  3. import indicator_pb2
  4. import indicator_pb2_grpc
  5. def run():
  6. with grpc.insecure_channel("localhost:50051") as channel:
  7. stub = indicator_pb2_grpc.IndicatorStub(channel)
  8. response = stub.GetMACD(
  9. indicator_pb2.MACDRequest(
  10. start_date="2023-01-01",
  11. end_date="2023-12-31",
  12. )
  13. )
  14. print("indicator client received: ")
  15. print(response)
  16. if __name__ == "__main__":
  17. run()

3.5. 运行效果

加入客户端和服务端代码后,最后的文件结构如下:
image.png

测试时,先启动服务:

  1. $ python.exe .\idc_server.py
  2. Server started, listening on 50051

然后启动客户端看效果:

  1. $ python.exe .\idc_client.py
  2. indicator client received:
  3. macd {
  4. date: "2023-01-01"
  5. open: 1.1
  6. close: 2.1
  7. high: 3.1
  8. low: 0.1
  9. macd: 2.5
  10. }
  11. macd {
  12. date: "2023-01-01"
  13. open: 2.2
  14. close: 4.2
  15. high: 6.2
  16. low: 0.2
  17. macd: 5
  18. }
  19. macd {
  20. date: "2023-01-01"
  21. open: 3.3
  22. close: 6.3
  23. high: 9.3
  24. low: 0.3
  25. macd: 7.5
  26. }
  27. macd {
  28. date: "2023-01-01"
  29. open: 4.4
  30. close: 8.4
  31. high: 12.4
  32. low: 0.4
  33. macd: 10
  34. }

4. 传输文件/图片

除了上面的返回列表数据的接口比较常用以外,我用的比较多的还有一种接口就是返回图片。
将使用pythonmatplotlib等库生成的分析结果图片提供给其他系统使用。

开发的步骤和上面是一样的。

4.1. 定义服务接口

定义文件相关的服务接口,文件的部分需要加上stream关键字,也就是流式数据。

  1. syntax = "proto3";
  2. package idc;
  3. // 定义服务,也就是对外提供的功能
  4. service IndicatorGraph {
  5. rpc GetMACDGraph(MACDGraphRequest) returns (stream MACDGraphReply) {}
  6. }
  7. // 请求的参数
  8. message MACDGraphRequest {
  9. string start_date = 1; // 交易开始时间
  10. string end_date = 2; // 交易结束时间
  11. }
  12. // 返回的内容,是一个图片
  13. message MACDGraphReply {
  14. bytes macd_chunk = 1;
  15. }

注意,定义服务接口GetMACDGraph时,返回值MACDGraphReply前面加上stream关键字。
返回的文件内容是 bytes 二进制类型。

4.2. 生成模板代码

执行命令:

  1. python -m grpc_tools.protoc -I./protos --python_out=. --pyi_out=. --grpc_python_out=. ./protos/indicator_graph.proto

生成3个文件:

  1. indicator_graph_pb2.py
  2. indicator_graph_pb2.pyi
  3. indicator_graph_pb2_grpc.py

4.3. server端代码

首先,生成一个MACD指标的图片(macd.png)。
image.png

然后,服务端的代码主要就是按块读取这个文件并返回。

  1. import grpc
  2. import indicator_graph_pb2
  3. import indicator_graph_pb2_grpc
  4. class IndicatorGraph(indicator_graph_pb2_grpc.IndicatorGraphServicer):
  5. def GetMACDGraph(self, request, context):
  6. chunk_size = 1024
  7. with open("./macd.png", mode="rb") as f:
  8. while True:
  9. chunk = f.read(chunk_size)
  10. if not chunk:
  11. return
  12. response = indicator_graph_pb2.MACDGraphReply(macd_chunk=chunk)
  13. yield response

4.4. client端代码

客户端的代码也要相应修改,不再是一次性接受请求的结果,而是循环接受,直至结束。

  1. import grpc
  2. import indicator_graph_pb2
  3. import indicator_graph_pb2_grpc
  4. def run():
  5. with grpc.insecure_channel("localhost:50051") as channel:
  6. stub = indicator_graph_pb2_grpc.IndicatorGraphStub(channel)
  7. print("indicator client received: ")
  8. with open("./received_macd.png", mode="wb") as f:
  9. for response in stub.GetMACDGraph(
  10. indicator_graph_pb2.MACDGraphRequest(
  11. start_date="2023-01-01",
  12. end_date="2023-12-31",
  13. )
  14. ):
  15. f.write(response.macd_chunk)

客户端接收完成后,图片保存在 received_macd.png 中。

实际执行后,图片可以正常保存并显示。

5. 回顾

本篇是最近用gPRC封装python数据分析相关业务过程中一些简单的总结。

这里没有对gPRC做系统的介绍,它的官方文档已经非常完善,而且文档中针对主流编程语言的示例也都有。
本篇笔记中的两个示例虽然简单,却是我用的最多的两种情况:
一种是返回对象数组:是为了将pandasnumpy等库处理后的数据返回出来供其他系统使用;
一种是返回文件/图片:是为了将matplotlibseaborn等库生成的分析图片返回出来供其他系统使用。

目前gPRC对我最大的好处是,它提供了一种稳定可靠的,将python强大的数据分析能力结合到其他系统中的能力。

原文链接:https://www.cnblogs.com/wang_yb/p/18019802

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号