Заголовок:
Ошибка импорта gRPC Python для сгенерированного hello_pb2. Файлы py и hello_pb2_grpc.py
Вопрос:
У меня есть hello.proto на стороне сервера. На стороне клиента я выполнил следующую команду protoc для создания необходимых файлов Python:
Код: Выделить всё
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
Код: Выделить всё
hello_pb2.pyКод: Выделить всё
hello_pb2_grpc.py
Код: Выделить всё
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()
Код: Выделить всё
HelloRequestКод: Выделить всё
hello_pb2.pyfile hello_pb2.py выглядит так (сгенерировано 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)
При попытке запустить сервер, я получаю ошибку импорта, связанную с Hello_pb2 (специально Hellorequest и Helloreply ). Другой импорт в скрипте работает нормально, но этот конкретный импорт стерж. что файл hello.proto на стороне сервера правильно определен и что проток генерирует ожидаемый выход.
Запуск команды Protoc в На стороне клиента и подтвердил, что генерируются hello_pb2.py и hello_pb2_grpc.py . br /> Попытка настроить пути импорта, но ошибка сохраняется. > Не могли бы вы помочь мне определить, что может вызвать ошибку импорта? В частности, почему импорт для Hellorequest и helloreply сбой, в то время как другие импорты работают правильно? Сгенерированные файлы доступны и импортируются правильно в скрипте на стороне клиента? , фрагменты кода и запрос на помощь. Теперь другим должно быть проще понять проблему и оказать помощь!
Подробнее здесь: https://stackoverflow.com/questions/793 ... port-error
Мобильная версия