ModuleNotFoundError when Importing gRPC pb2 File Generated by Protoc in Python

553 Views Asked by At

I'm encountering a ModuleNotFoundError when trying to import a generated gRPC module in Python.

In my project, I have a file structure like this:

from test.api.grpc_test_cases.specific_folder.api_pb2
  • specific_folder contains a proto_files folder with .proto files.
  • specific_folder also has test.py files and generated files together.

Here's what my protoc commands look like:

  1. First, I generate D.proto because it imports into two other other proto files:
python3 \
-m grpc_tools.protoc \
-I proto_files \
--python_out=. \
--grpclib_python_out=. \
D.proto
  1. Then, I generate the other protobuf files (A.proto, B.proto, C.proto), which import D.proto:
python3 \
-m grpc_tools.protoc \
-I proto_files \
--python_out=. \
--grpclib_python_out=. \
proto_files/A.proto \
proto_files/B.proto \
proto_files/C.proto

In my test file, when I try to import a the generated pb2 file, I get the following error:

ModuleNotFoundError: No module named 'api_pb2'

Here's how I'm trying to import it:

from file.innerfile.innermostfile.api.api_pb2 import ServiceRequest

I've tried several things to resolve this issue, including:

  • Checking the Python path to ensure the generated modules are in the search path.
  • Using both relative and absolute paths in the import statement.
  • Generating all protobuf files in a single compiler command.
  • Adding "from . import api_pb2" in the grpc.py file.

I expected that one of these approaches would resolve the ModuleNotFoundError issue, allowing me to import ServiceRequest to use in my pytest tests without any errors. I want to use ServiceRequest from the pb2 file to create a response object using pytest like this:

response = ServiceRequest()
response.name = "John"
response.id = 123
response.timestamp = "2023-09-18T12:00:00"
0

There are 0 best solutions below