如何使用Python向gRPC服务器发送符合image.proto定义的图像旋转请求
问题定位
现有代码存在三类不匹配的逻辑错误,会导致请求无法正常通联:
- 客户端请求构造错误:空的
NLImageRotateRequest没有填充必填的旋转角度、图像内容字段,且调用stub方法时多传了inputfile参数——gRPC的一元调用接口仅接受构造完成的请求对象作为入参,本地文件路径不需要传给接口层,客户端本地完成读图转换即可。 - 客户端调用逻辑错误:没有接收接口返回的响应内容,调用完直接结束,没法拿到服务端回传的处理后图像。
- 服务端结构错误:server初始化、绑定端口的代码被写在了Servicer类定义内部,根本不会被执行;且两个接口方法的返回值不符合proto定义的格式,引用了非公开的内部类
_NLIMAGE,没有返回带有效字段的NLImage实例。
正确实现方式
客户端调整
按照下面的流程补全逻辑即可:
- 本地读取目标图像,把图像的元数据和字节流填充到
NLImage结构中 - 结合用户传入的旋转参数,构造完整的
NLImageRotateRequest对象 - 调用stub的
RotateImage方法,仅传入构造好的请求对象,接收返回的NLImage响应 - 把响应中的图像字节流写入本地输出路径
示例代码片段:
import io from PIL import Image # 读取本地图片,构造NLImage with open(inputfile, "rb") as f: raw_img_bytes = f.read() img = Image.open(io.BytesIO(raw_img_bytes)) nl_img = image_pb2.NLImage( color = img.mode == "RGB", data = raw_img_bytes, width = img.width, height = img.height ) # 映射旋转参数到proto定义的枚举值 rotate_enum_map = { "none": image_pb2.NLImageRotateRequest.Rotation.NONE, "90": image_pb2.NLImageRotateRequest.Rotation.NINETY_DEG, "180": image_pb2.NLImageRotateRequest.Rotation.ONE_EIGHTY_DEG, "270": image_pb2.NLImageRotateRequest.Rotation.TWO_SEVENTY_DEG } # 构造完整的旋转请求 rotate_req = image_pb2.NLImageRotateRequest( rotation = rotate_enum_map[rotate], image = nl_img ) # 调用接口,仅传请求对象,接收响应 resp_img = stub.RotateImage(rotate_req) # 把返回的图像字节流写入输出文件 with open(outputfile, "wb") as f: f.write(resp_img.data)
服务端调整
把代码结构调整为标准gRPC服务写法:
- Servicer类内部仅保留两个接口的处理逻辑,从请求中取出参数,完成图像旋转/滤波的实际计算后,构造带有效字段的
NLImage对象返回 - 注意server初始化的代码不能写在Servicer类内部,类定义时不会执行内部的server启动逻辑,会导致服务根本无法监听端口,要把server实例化、服务注册、端口绑定、启动的代码移出Servicer类,放在类定义的外部,确保服务能正常启动监听
示例代码结构:
class NLImageServiceServicer(image_pb2_grpc.NLImageServiceServicer): def RotateImage(self, request, context): print("Request to rotate image received") # 从请求中取出旋转角度、原始图像数据 target_rotation = request.rotation src_img = request.image # 这里替换为实际的图像旋转处理逻辑,得到处理后的图像字节流、宽、高、彩色标识 processed_bytes = b"" processed_w = 0 processed_h = 0 is_color = True # 构造符合proto定义的响应对象 return image_pb2.NLImage( color=is_color, data=processed_bytes, width=processed_w, height=processed_h ) def MeanFilter(self, request, context): print("Request to filter received") # 替换为实际的均值滤波处理逻辑 return image_pb2.NLImage() # 以下代码必须放在类定义外部,才能正常执行 server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) image_pb2_grpc.add_NLImageServiceServicer_to_server(NLImageServiceServicer, server) host = "0.0.0.0" port = "5000" server.add_insecure_port(f"{host}:{port}") server.start() print(f"Server started ...on {host}:{port}") server.wait_for_termination()
内容的提问来源于stack exchange,提问作者codigomonstruo
相关产品推荐
相关产品推荐

