How to pass array in a gRPC?

Asked

Viewed 120 times

0

I’m testing some code using gRPC with the Python language, and I’m not able to manipulate array. The code consists of passing an array per parameter, the server receives this array and sorts.

code . proto

syntax = "proto3";

message Number {
  repeated int32 value = 1;

}

Code sorts.py

def organiza(vetor):
vetor.sort()
return vetor

server.py

class OrdenaServicer(ordena_pb2_grpc.OrdenaServicer):

def Organiza(self, request, context):
    response = ordena_pb2.Number()
    response.value = int(ordena.organiza(request.value))
    return response


service Ordena {
  rpc Organiza(Number) returns (Number) {}
}

client py.

# create a stub (client)
stub = ordena_pb2_grpc.OrdenaStub(channel)

# create a valid request message
vetor = [23,65,8,3,89,34,6,22,12,5,9,54]
number = ordena_pb2.Number(value=vetor)

# make the call
response = stub.Organiza(number)

The code itself is very simple, consists only of a basic ordering, but I am not able to pass the vector as parameter. Every time I try to make a mistake:

Typeerror: int() argument must be a string, a bytes-like Object or a number, not 'google.protobuf.pyext. _message.Repeatedscalarcontainer'

1 answer

2


The service Organiza expects an instance of the Number class as return. To instantiate an object of this class, you need to pass a list of integers as an argument, since that is what was specified in the proto. Therefore, below follows the correct service code:

def Organiza(self, request, context):
    vetor_ordenado = ordena.organiza(request.value)
    return ordena_pb2.Number(value=vetor_ordenado)

But the main reason the exception has arisen TypeError was because you tried to convert a list into a whole:

int(ordena.organiza(request.value))
  • Thanks! It worked right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.