任何人都可以共享任何Python服务器和客户端代码,这些代码演示了类似于https://jbrandhorst.com/post/grpc-binary-blob-stream/的gRPC中分块的使用吗?谢谢。
答案 0 :(得分:0)
这是Chunker的gRPC Python版本。使用Python生成器实现服务程序中分块的主要逻辑。
# server.py
_CHUNKER_SIZE = 4
_DATA_TO_SEND = 'Hello gRPC Python World!'
def _chunk_bytes(data, chunker_size):
index = 0
while index < len(data):
yield chunker_pb2.Chunk(
chunk=data[index:index+chunker_size]
)
index += chunker_size
class Chunker(chunker_pb2_grpc.ChunkerServicer):
@staticmethod
def Chunker(request, unused_context):
return _chunk_bytes(
_DATA_TO_SEND,
_CHUNKER_SIZE)
客户端很简单。它接收响应并将其连接起来。
with grpc.insecure_channel('localhost:50051') as channel:
stub = chunker_pb2_grpc.ChunkerStub(channel)
response_iterator = stub.Chunker(empty_pb2.Empty())
received_bytes = bytes()
for response in response_iterator:
received_bytes += response.chunk
print('Concatenated Response:')
print(received_bytes)
Gist中提供了完整版本:https://gist.github.com/lidizheng/825f1b255767a90fb3a5d4be54071678