python gRPC:根据.protobuf文件生成py代码、grpc转换为http协议对外提供服务

python GRPC:根据.protobuf文件生成py代码

Protobuf文档:https://developers.google.com/protocol-buffers/docs/proto3#nested
GRPC 函数参考:https://grpc.github.io/grpc/python/grpc.html

grpcio-tools

官网:https://www.cnpython.com/pypi/grpcio-tools

grpcio-tools是gRPC Python 工具的包。 主要用于根据.protobuf文件生成客户方与服务方代码。

库grpcio-tools的作用是把proto文件转译为Python代码。

安装和使用

python -m pip install grpcio-tools

python -m grpcio-tools.protoc 来编译生成python文件,引用即可。 pb2后缀的是protobuf带的消息,grpc结尾的是grpc里面定义的service和rpc等类

python GRPC的官网示例

python GRPC的官网示例
参考URL: https://www.jianshu.com/p/6f5df4f2fd7c

grpc转换为http协议对外提供服务

grpc转换为http协议对外提供服务
参考URL; https://blog.51cto.com/u_15067234/4067405

使用grpc的优点很多,二进制的数据可以加快传输速度,基于http2的多路复用可以减少服务之间的连接次数,和函数一样的调用方式也有效的提升了开发效率。

不过使用grpc也会面临一个问题,我们的微服务对外一定是要提供Restful接口的,如果内部调用使用grpc,在某些情况下要同时提供一个功能的两套API接口,这样就不仅降低了开发效率,也增加了调试的复杂度。于是就想着有没有一个转换机制,让Restful和gprc可以相互转化。

解决方案, https://github.com/grpc-ecosystem/grpc-gateway

工作问题总结

grpc-ecosystem/grpc-gateway/third_party/googleapis: warning: directory does not exist.

问题描述:
.proto 文件中使用了 import "google/api/annotations.proto";
使用 python -m grpc_tools.protoc -I=./proto --python_out=test xxx.proto 后报错:grpc-ecosystem/grpc-gateway/third_party/googleapis: warning: directory does not exist.

问题分析:
用到三方proto文件

解决方案:
下载安装这个googleapis

go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@latest
find / -name googleapis

根据你的情况,组装如下命令:

python -m grpc_tools.protoc -I=./proto -I=$GOPATH/pkg/mod/github.com/grpc-ecosystem/[email protected]/third_party/googleapis --grpc_python_out=service myxxx_service.proto
  • -I= 指的是从哪找.proto文件

猜你喜欢

转载自blog.csdn.net/inthat/article/details/129323707