我想知道 Go 中的 gRPC 服务和 Python 中的客户端的兼容性。
例如,如果服务是在 Go 中实现的,它将具有如下签名:
...
func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
...
}
...
func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
...
}
...
func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
...
}
...
func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
...
}
请注意如何返回error
对象。
现在,如果我必须在 Python 中实现客户端,它将是这样的:
feature = stub.GetFeature(point)
for received_route_note in stub.RouteChat(sent_route_note_iterator):
Go 服务实现返回的error
字段会发生什么情况?如果服务器端出现错误,如何在 Python 客户端中处理?
gRPC 提供适合所用语言的错误处理。
正如你所指出的,在 Go 服务器中,你返回一个错误:
func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
for {
in, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
...
在 Python 客户端中,您可以在try
语句中执行 API 调用(人为示例,因为官方文档没有演示这一点(:
while True:
try:
received_route_note = stub.RouteChat(sent_route_note_iterator)
except grpc.Error as e:
print(e.details())
break
相反,在 Python 服务器中,您可以设置上下文并选择性地引发异常:
Python 生成的代码参考中的示例:
def TellFortune(self, request, context): """Returns the horoscope and zodiac sign for the given month and day. errors: invalid month or day, fortune unavailable """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
来自 GRPC 存储库的示例
def UnUn(self, request, context): if _application_common.UNARY_UNARY_REQUEST == request: return _application_common.UNARY_UNARY_RESPONSE else: context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details('Something is wrong with your request!') return services_pb2.Down()
在 Go 客户端中,error
对象是(结果参数之一(:
stream, err := client.RouteChat(ctx)
if err != nil {
log.Fatalf("%v.RouteChat(_) = _, %v", client, err)
}
不幸的是,官方文档似乎没有明确涵盖错误处理实践。
我找到的一个很好的第三方参考是 http://avi.im/grpc-errors/