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

2024-09-27 21:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道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

^{pr2}$

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


Tags: theingostreamgrpc客户机ifis
1条回答
网友
1楼 · 发布于 2024-09-27 21:33:33

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调用(人为的示例,因为官方文档没有演示这一点):

^{pr2}$

相反,在Python服务器中,您可以设置上下文并(可选)引发异常:

  • {来自a2}:

    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/找到了一个很好的第三方参考

相关问题 更多 >

    热门问题