Ram
Ram

Reputation: 13

python How to handle grpc stream after stream cancel() is called

I'm trying to write a python client to terminate a gRPC stream

Proto:

rpc Start (StartParameters) returns (stream Progress) {}

In the client when I'm ready to terminate the stream, I tried calling stream.cancel() and then when I print the events of the captured stream, it doesn't print the events. I see the exception

<_Rendezvous of RPC that terminated with:
    status = StatusCode.CANCELLED
    details = "Locally cancelled by application!"
    debug_error_string = "None"

client.py

stream = self.stub.Start(params)
time.sleep(120)
stream.cancel()

for event in stream:
    print(event)

Can somebody please help me with a python code to cancel this stream and print the events in the stream.

Upvotes: 0

Views: 2632

Answers (1)

Richard Belleville
Richard Belleville

Reputation: 1620

The problem is that you're cancelling the stream before you actually begin iterating over it. Try cancelling the RPC asynchronously, on another thread.

stream = self.stub.Start(params)

def _cancel_after_a_while():
    time.sleep(120)
    stream.cancel()

cancellation_thread = threading.Thread(target=_cancel_after_a_while)
cancellation_thread.start()

for event in stream:
    print(event)

Upvotes: 1

Related Questions