I have a grpc repo included in a python project repo as a submodule at src/grpc/protobuf
with the following example structure:
protobuf/
|
|-data_structs/
| |-example_structA.proto
| |-example_structB.proto
|
|-messages/
| |-example_messageA.proto
| |-example_messageB.proto
|
|-services/
|-example_service.proto
With simplified example implementations:
//example_structA.proto
syntax = "proto3"
message example_structA {
int id = 1;
}
//example_structB.proto
syntax = "proto3"
import "data_structs/example_structA.proto";
message example_structB {
int id = 1;
repeated example_structA items = 2;
}
//example_messageA.proto
syntax = "proto3"
import "data_structs/example_structB.proto"
message example_messageA {
string info = 1;
example_structB data = 2;
}
//example_messageB.proto
syntax = "proto3"
message example_messageB {
string status = 1;
}
//example_service.proto
syntax = "proto3"
import "messages/example_messageA.proto";
import "messages/example_messageB.proto";
service example_service {
rpc SendMessage (example_messageA) returns (example_messageB) {}
}
I am generating the python code with the following command, run from the python projects root dir:
find src/grpc/protobuf -name "*.proto" | xargs python -m grpc_tools.protoc =I=./src/grpc/protobuf --python_out=./src/grpc/generated --grpc_python_out=./src/grpc/generated
This correctly generates .py files in the src/grpc/generated directory, and places them into subdirectories that mimic the proto repo structure. e.g. the files for example_structB
are located at src/grpc/generated/data_structs/example_structB_pb2.py
and src/grpc/generated/data_structs/example_structB_pb2_grpc.py
messages are in the src/grpc/generated/messages
directory, etc.
These generated files have faulty imports generated though.
example_structB_pb2.py
has from data_structs import example_structA_pb2
This should be from . import example_structA_pb2
or simply import example_structA_pb2
example_messageA_pb2.py
has from data_structs import example_structB_pb2
This should be from ..data_structs import example_structB_pb2
So on and so forth. Services importing messages should be from ..messages import
instead of just from messages import
I have not had any issues using this directory/proto structure and generation in java or c++. Is there any way to resolve this for python generated code?