Reputation: 11
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
Here's what my protoc commands look like:
python3 \
-m grpc_tools.protoc \
-I proto_files \
--python_out=. \
--grpclib_python_out=. \
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:
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"
Upvotes: 1
Views: 2526
Reputation: 67
Because protoc's path logic is depend on the location of the proto file.
The right way is let the proto file be in the same folder as the path to the python file you want to generate.
Example:
app
├── service (python module, directory)
└── proto/
├── __init__.py
├── api.proto
├── api_pb2.py
└── api_pb2_grpc.py
Go to the app
(Root directory, which you run python -m service
command).
Run: protoc -I. --python_out=. --grpc_python_out=. ./proto/api.proto
All the .
relative to the location of the proto file.
Also see: https://stackoverflow.com/a/76946302/15715806
Upvotes: 0