Go中的gRPC服务器与Python中的客户端之间的兼容性

问题描述 投票:2回答:1

我想知道Go中的gRPC服务和Python中的客户端的兼容性。

例如if the service is implemented in 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对象。

现在,如果我必须implement the client in Python it will be something like this

feature = stub.GetFeature(point)
for received_route_note in stub.RouteChat(sent_route_note_iterator):

Go服务实现返回的error字段会发生什么?如果服务器端出现错误,如何在Python客户端中处理?

python go grpc
1个回答
3
投票

gRPC提供适合所用语言的错误处理。

如你所知,在Go server中你会返回一个错误:

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 Generated Code Reference的例子: 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 repository的例子 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 client中,error对象是(其中一个)结果参数:

stream, err := client.RouteChat(ctx)
if err != nil {
    log.Fatalf("%v.RouteChat(_) = _, %v", client, err)
}

不幸的是,官方文档似乎没有明确涵盖错误处理实践。

我找到的一个很好的第三方参考是在http://avi.im/grpc-errors/

© www.soinside.com 2019 - 2024. All rights reserved.