gpt4 book ai didi

python - 如何在 asyncio 中使用 gRPC

转载 作者:行者123 更新时间:2023-12-03 23:21:29 26 4
gpt4 key购买 nike

在哪里可以找到将 gRPC 与 asyncio 结合使用的示例,特别是如何使用 gRPC 和 asyncio 创建客户端

最佳答案

从 1.32 版开始,gRPC 现在在其 Python API 中支持 asyncio .如果您使用的是早期版本,您仍然可以通过实验性 API 使用 asyncio API:from grpc.experimental import aio .一个异步 hello world example也已添加到 gRPC 存储库中。以下代码是示例客户端的副本:

import logging                                                                  
import asyncio
from grpc import aio

import helloworld_pb2
import helloworld_pb2_grpc


async def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
async with aio.insecure_channel('localhost:50051') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = await stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)


if __name__ == '__main__':
logging.basicConfig()
asyncio.run(run())
my other answer关于如何实现服务器。

关于python - 如何在 asyncio 中使用 gRPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com