I thought this would just be a quick and easy problem to solve, but alas it is not.
I'm trying to find a way of sending a "CancellationToken" from my python client implementation which communicates with my C# Server.
With the C# client implementation I can simply implement:
var tokenSource = new CancellationTokenSource();
while (await priceResponse.ResponseStream.MoveNext(tokenSource.Token))
The Server code:
public async override Task Prices(PricesRequest request, IServerStreamWriter<PricesResponse> responseStream, ServerCallContext context)
{
...
while (!context.CancellationToken.IsCancellationRequested)
{
...
Does anyone know how to implement the cancellation pattern using python to communicate with the C# Server, or am I going about this the wrong way?
Thanks for any advice or opinions :)
I tried this - but to no avail...
class CancellationToken:
def __init__(self):
self._is_canceled = False
def is_canceled(self):
return self._is_canceled
def cancel(self):
self._is_canceled = True
But I'm relatively poor at python - so took this from some other more enlightened soul :)
Here's the Python code (although like I said I'm no expert)
import grpc
import greeting_pb2
import greeting_pb2_grpc
import pricing_pb2
import pricing_pb2_grpc
import os
import logging
_LOGGER = logging.getLogger(__name__)
_SERVER_HOST = "localhost"
_SERVER_PORT = "50051"
def pricing_client():
try:
_LOGGER.info(f"Attempting to connecto {_SERVER_HOST}:{_SERVER_PORT}...")
channel = grpc.insecure_channel(f"{_SERVER_HOST}:{_SERVER_PORT}")
pricingStub = pricing_pb2_grpc.PricingServiceStub(channel)
_LOGGER.info("Channel Connection made, stubs created...")
myrequest = greeting_pb2.GreetingRequest(greeting=mygreeting)
myprice = pricing_pb2.Price(instrument="BP")
mypricerequest = pricing_pb2.PricesRequest(price=myprice)
pricingResponse = pricingStub.Prices(mypricerequest)
_LOGGER.debug(f"Pricing response executed successfully {pricingResponse}")
prices = 0
for price in pricingResponse:
_LOGGER.debug(f"Price received: {price}")
prices += 1
if(prices == 10):
# trying to cancel here, but for now I just exit the client
return
except:
_LOGGER.error(f"An error occured - please check the server is runing @ {_SERVER_HOST}:{_SERVER_PORT}")
finally:
_LOGGER.info("Application exiting...")
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
pricing_client()