python的grpc无法正常发送请求

我用的是python的grpcio这个包,中间一度出现_InactiveRpcError,并且是时好时坏,报错也很迷惑,让人写代码写到怀疑人生。

<_InactiveRpcError of RPC that terminated with:
        status = StatusCode.UNKNOWN
        details = "Exception calling application: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.UNKNOWN
        details = "Exception calling application: 
        。。。。。。(省略具体错误)

这个时候,检查一下是否有以下两个低级错误:

  1. 设置了全局代理
  2. 检查一下后台是否有残留的孤儿进程或者僵尸进程,在一个端口上只能启动一个grpc服务,如果有多个的话会出现混乱(我是因为这个问题折腾了一晚上)
### 如何使用 Python 发送 gRPC 请求 要通过 Python 实现发送 gRPC 请求的功能,首先需要完成必要的准备工作并编写客户端代码。以下是具体说明: #### 安装依赖库 为了能够正常运行 gRPC 功能,需确保已安装 `grpcio` 库以及对应的工具链。可以通过以下命令安装所需包: ```bash pip install grpcio grpcio-tools ``` 此操作会下载并安装 gRPC 的核心库及其编译工具[^4]。 #### 编写 `.proto` 文件 在实际应用中,通常先定义协议缓冲区(Protocol Buffers)文件即 `.proto` 文件,它描述了服务接口和服务端/客户端间传递的消息结构。例如创建名为 `route_guide.proto` 的文件如下所示: ```protobuf syntax = "proto3"; package routeguide; service RouteGuide { rpc GetFeature(Point) returns (Feature) {} } message Point { int32 latitude = 1; int32 longitude = 2; } message Feature { string name = 1; Point location = 2; } ``` 接着利用 `protoc` 命令生成相应的 Python 类型绑定文件: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./route_guide.proto ``` 上述指令会在当前目录下生成两个新文件:`route_guide_pb2.py` 和 `route_guide_pb2_grpc.py`[^2]。 #### 创建客户端脚本 有了这些自动生成的模块之后就可以着手构建客户端逻辑部分了。下面给出一段完整的例子展示怎样发起一次远程调用过程。 ```python import grpc from route_guide_pb2 import Point, Feature from route_guide_pb2_grpc import RouteGuideStub def get_feature(stub): point = Point(latitude=409146138, longitude=-74618892) feature = stub.GetFeature(point) if not feature.name: print(f"No feature found at {point.latitude}, {point.longitude}") else: print(f"Found feature called \"{feature.name}\" at " f"{feature.location.latitude},{feature.location.longitude}") if __name__ == '__main__': with grpc.insecure_channel('localhost:50051') as channel: stub = RouteGuideStub(channel) get_feature(stub) ``` 在此段程序里我们实例化了一个未加密连接到本地服务器地址上的通道对象,并基于这个通道获取到了 Stub 接口代理实例;随后调用了其下的某个方法传入参数得到返回结果加以处理显示出来[^1]^。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛钦亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值