先问问题,再看上下文。如何使用异步 gRPC python 服务器基于从客户端取消 RPC 来执行某些服务器端操作(例如清理)?
在我的微服务中,我有一个asynciogRPC 服务器,其主要 RPC 是双向流。
在客户端(也使用 asyncio),当我取消某些操作时,它会引发一个asyncio.CancelledError被捕获且不会被grpc核心重新引发的异常:
except asyncio.CancelledError:
_LOGGER.debug('RPC cancelled for servicer method [%s]', _decode(rpc_state.method()))
Run Code Online (Sandbox Code Playgroud)
asyncio.CancelledError所以我不能依赖于在我自己的代码中捕获,因为它是预先捕获的并且不会重新引发。
共享上下文应该包含有关 RPC 是否在客户端被取消的信息,通过.cancel()从 RPC 调用进行调用并能够通过调用查看它是否被取消.cancelled():
https://grpc.github.io/grpc/python/grpc_asyncio.html#shared-context
抽象取消()
Run Code Online (Sandbox Code Playgroud)Cancels the RPC. Idempotent and has no effect if the RPC has already terminated. Returns A bool indicates if the cancellation is performed or not. Return type bool摘要取消()
Run Code Online (Sandbox Code Playgroud)Return True if the RPC is cancelled. The …