Getting started with grpc django throws import error

Sure! Here’s your question formatted according to Stack Overflow standards:


Title: gRPC Python Import Error for Generated hello_pb2.py and hello_pb2_grpc.py Files


Question:

I have a hello.proto file on the server side. On the client side, I ran the following protoc command to generate the necessary Python files:

python3 -m grpc_tools.protoc -I. -Iproto-lib/src/main/proto -Iproto-lib/src/main/proto/common --python_out=./publons/scholarly_person_master_service --grpc_python_out=./app proto-lib/src/main/proto/hello.proto

This command created two files on the client side:

  • hello_pb2.py
  • hello_pb2_grpc.py

I then created a Python script on the client side to use these files and set up a gRPC server. The code looks as follows:

import grpc
from concurrent import futures
from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2 import HelloReply, HelloRequest
from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2_grpc import SimpleServicer, add_SimpleServicer_to_server

# Implementing the service
class SimpleService(SimpleServicer):
    def SayHello(self, request, context):
        # This method handles the gRPC call and returns a response
        response = HelloReply(message=f"Hello, {request.name}!")
        return response

# Running the gRPC server
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    add_SimpleServicer_to_server(SimpleService(), server)  # Registering the service
    server.add_insecure_port('[::]:50051')
    server.start()
    print("Server started on port 50051")
    server.wait_for_termination()

if __name__ == '__main__':
    serve()

However, when I try to run the server, I encounter an error related to the imports (HelloRequest and HelloReply), even though other imports in the script are working fine.

hello_pb2.py File

The hello_pb2.py file looks like this (generated by protoc):

# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: sp-master-ri-proto-lib/src/main/proto/hello.proto
# Protobuf Python Version: 5.29.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(
    _runtime_version.Domain.PUBLIC,
    5,
    29,
    0,
    '',
    'sp-master-ri-proto-lib/src/main/proto/hello.proto'
)
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n1sp-master-ri-proto-lib/src/main/proto/hello.proto\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t22\n\x06Simple\x12(\n\x08SayHello\x12\r.HelloRequest\x1a\x0b.HelloReply\"\x00\x42=\n(com.clarivate.singularity.spmaster.protoB\x0fHelloWorldProtoP\x01\x62\x06proto3')

_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sp_master_ri_proto_lib.src.main.proto.hello_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
  _globals['DESCRIPTOR']._loaded_options = None
  _globals['DESCRIPTOR']._serialized_options = b'\n(com.clarivate.singularity.spmaster.protoB\017HelloWorldProtoP\001'
  _globals['_HELLOREQUEST']._serialized_start=53
  _globals['_HELLOREQUEST']._serialized_end=81
  _globals['_HELLOREPLY']._serialized_start=83
  _globals['_HELLOREPLY']._serialized_end=112
  _globals['_SIMPLE']._serialized_start=114
  _globals['_SIMPLE']._serialized_end=164
# @@protoc_insertion_point(module_scope)

Issue

When attempting to run the server, I receive an import error related to hello_pb2 (specifically HelloRequest and HelloReply). Other imports in the script are working fine, but this particular import is failing.

What I Have Tried

  1. Verified that the hello.proto file on the server side is correctly defined and that protoc generates the expected output.
  2. Ran the protoc command on the client side and confirmed that hello_pb2.py and hello_pb2_grpc.py are being generated.
  3. Checked the paths to ensure everything is correctly referenced.
  4. Attempted to adjust the import paths, but the error persists.

Request for Assistance

Could you help me identify what might be causing the import error? Specifically, why is the import for HelloRequest and HelloReply failing while other imports work correctly?

Additionally, are there any other steps I should follow to ensure that the generated files are accessible and imported correctly in the client-side script?


This version of your question follows Stack Overflow conventions, with a clear title, problem description, code snippets, and a request for assistance. It should now be easier for others to understand the issue and provide help!

Back to Top