调用PredictionServiceStub时出现'Channel'无'unary_unary'属性错误求助
AttributeError: 'Channel' object has no attribute 'unary_unary' with TensorFlow Serving gRPC Stub
这个问题的核心原因是gRPC版本与TensorFlow Serving的API不兼容,你用的是gRPC旧版本的API来创建Channel,而TensorFlow Serving的PredictionServiceStub需要新版gRPC的Channel对象。
问题根源
你代码里用的grpc.implementations.secure_channel是gRPC 1.0之前的旧API,它返回的是旧版的Channel类型,这个类型没有unary_unary方法——而TensorFlow Serving的gRPC stub(比如PredictionServiceStub)依赖新版gRPC Channel的这个方法来定义服务调用。
修复方法
你需要改用新版gRPC的API来创建安全通道,步骤如下:
- 确保安装了较新版本的grpcio
先检查你的grpcio版本,建议升级到1.10+以上:
pip install --upgrade grpcio grpcio-tools
- 修改代码中的Channel创建逻辑
把旧的implementations相关代码替换成新版gRPC的API:
# 替换原来的implementations导入 import grpc @app.route('/LangDet', methods=['POST']) def do_inference(): # ... 其他代码保持不变 ... model_host = model_info["modelServers"][latest_version[1]]["endpoints"][0] # 改用新版grpc的ssl证书创建方法 credentials = grpc.ssl_channel_credentials(root_certificates=bytes(model_host["caCrt"], 'ascii')) # 用新版grpc.secure_channel创建通道,格式是"host:port" channel = grpc.secure_channel(f"{model_host['host']}:{model_host['port']}", credentials) stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) # ... 后续推理代码 ...
为什么这样改?
新版gRPC已经废弃了grpc.implementations模块,所有通道创建都统一到grpc核心模块下的方法,比如grpc.secure_channel和grpc.insecure_channel,这些方法返回的Channel对象包含了TensorFlow Serving Stub需要的unary_unary、unary_stream等方法,能正确与服务端交互。
如果你还需要兼容旧代码,也可以尝试将旧版Channel转换为新版,但直接升级API是更稳妥的长期方案,也能避免其他潜在的兼容性问题。
内容的提问来源于stack exchange,提问作者Adam Krawczyk
相关产品推荐
相关产品推荐

