0

Long story short I am building a python grpc client that interacts with another team's GRPC server. Does python's grpc module have any sorting features?

response = client_stub.get_grpc_templates_stub(grpc_stub_method).ListTemplateRevisions(request=request, metadata=metadata_okta_token_and_env)

grpc_logger.debug(response.revisions)

The (part of) output I get is:

revisions {
  revision: "1"
  last_applied {
    seconds: 1667329109
  }
}
revisions {
  revision: "2"
  last_applied {
    seconds: 1667962055
  }
}

I need to grab the latest, in which case is revision: "2" and feed that to another gRPC call along with the rest of the original response. To be more accurate the above is a snippet of the entire output. I need to take the entire output, sort to latest revision and then pass that along but with only revision 2 dropping any older entries.

What have done already is converted the data object to JSON and then sorted it. But this means I need to convert it back to request for the next gRPC call. It works but wondering if I can skip some parts. Is there a more gRPC module feature only to do this? Meaning so that I can do it in a one liner instead of response --> convert to json ---> sort ---> build new request payload.

thanks

New2Python
  • 325
  • 1
  • 4
  • 17

1 Answers1

0

Python should (!) yield Python lists for protobuf repeated elements and you can sort Python lists and extract specific values.

So, assuming your proto is something like:

syntax = "proto3";

package foo;

import "google/protobuf/timestamp.proto";

message X {
  repeated Revision revisions = 1;
}

message Revision {
  string revision = 1;
  google.protobuf.Timestamp last_applied = 2;
}

And you add 3 revision:

from google.protobuf.timestamp_pb2 import Timestamp
import foo_pb2


x = foo_pb2.X()

r = x.revisions.add()
r.revision = "1"
r.last_applied.GetCurrentTime()

r = x.revisions.add()
r.revision = "2"
r.last_applied.GetCurrentTime()

r = x.revisions.add()
r.revision = "3"
r.last_applied.GetCurrentTime()

Then you can sort the list by the revision string:

x.revisions.sort(key=lambda x: x.revision, reverse=True)

And, as long as there's at least one result, you can return it:

if len(x.revisions)>0:
    print(x.revisions[0])
DazWilkin
  • 32,823
  • 5
  • 47
  • 88