Skip to main content
 首页 » 编程设计

python之您如何为具有多个 python 包的项目定义/组织 proto 文件

2025年01月19日9虾米哥

如何为包含两个(或更多)python 包的项目定义和组织 gRPC 原型(prototype)文件?

假设我有以下 monorepo 结构:

my_project/   
 | 
 |-my_client_pkg/ 
 |  |_Dockerfile 
 |  |_setup.py 
 |  |_my_client/ 
 |     |___init__.py 
 |     |_client.py 
 | 
  -my_server_pkg/ 
    |_Dockerfile 
    |_setup.py 
    |_my_server/ 
       |___init__.py 
       |_server.py 

我想使用 gRPC 将这两个服务连接在一起。我可以添加一个 protos/ 目录,其中包含适当的子目录,如下所示:

my_project/   
 | 
 |-protos/ 
 |  |_my_client_pkg/ 
 |  |  |_my_client.proto 
 |  | 
 |  |_my_server_pkg/ 
 |     |_my_server.proto 
 | 
 |-my_client_pkg/ 
 |  |_Dockerfile 
 |  |_setup.py 
 |  |_my_client/ 
 |     |___init__.py 
 |     |_client.py 
 | 
  -my_server_pkg/ 
    |_Dockerfile 
    |_setup.py 
    |_my_server/ 
       |___init__.py 
       |_server.py 

这有效:我可以使用正确的导入语句正确生成 .py 文件。这种方法的问题是我必须将所有内容从 my_client.proto 复制到 my_server.proto 中。如果我需要进行更改,它必须在两个文件中,显然容易出错。这似乎真的违背了 protobufs 的目的。

我应该如何组织我的原型(prototype)文件?是否可以在一个地方定义原型(prototype),然后使用原型(prototype) import 语句无缝复制定义?我应该做一些完全不同的事情吗?

编辑: 这是一个示例原型(prototype)文件:

syntax = "proto3"; 
 
message AbcRequest { 
  string utterance = 1; 
} 
 
message AbcResponse { 
  string value = 2; 
} 
 
service Abc { 
  rpc most_similar(AbcRequest) returns (AbcResponse) {} 
} 

我确实尝试在一个地方定义原型(prototype),然后导入它:

my_project/   
 | 
 |-protos/ 
 |  |-base.proto 
 |  |_my_client_pkg/ 
 |  |  |_my_client.proto 
 |  | 
 |  |_my_server_pkg/ 
 |     |_my_server.proto 

my_client.proto 和 my_server.proto 都有:

syntax = "proto3"; 
import "protos/base.proto"; 

但是,当我生成 python 代码时,*_grpc.py 文件中没有任何内容。我是否应该为导入工作做些其他事情?

请您参考如下方法:

protobuf import 语句允许您访问其他文件中定义的定义,但只会为该文件中定义的消息/服务生成代码。
语法=“proto3”; 导入“protos/base.proto”;

将生成空文件,因为此文件中没有定义服务/消息。

您导入的文件的代码将保存在 base_pb2_grpc 中。

我建议使用一个包含所有定义的 my_service.proto 文件,并只引用来自 my_client 和 my_server 包的生成的 _pb2_grpc.py 文件。