小编bru*_*ton的帖子

处理 gRPC python asyncio 中的客户端取消?

先问问题,再看上下文。如何使用异步 gRPC python 服务器基于从客户端取消 RPC 来执行某些服务器端操作(例如清理)?

在我的微服务中,我有一个asynciogRPC 服务器,其主要 RPC 是双向流。

在客户端(也使用 asyncio),当我取消某些操作时,它会引发一个asyncio.CancelledError被捕获且不会被grpc核心重新引发的异常:

https://github.com/grpc/grpc/blob/master/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi#L679

    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

抽象取消()

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 …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio grpc grpc-python

2
推荐指数
1
解决办法
1947
查看次数

标签 统计

grpc ×1

grpc-python ×1

python ×1

python-asyncio ×1