使用 Python 在 gRPC 中分块
Chunking in gRPC with Python
任何人都可以分享任何 Python 服务器和客户端代码来演示在 gRPC 中使用类似于 https://jbrandhorst.com/post/grpc-binary-blob-stream/ 的分块吗?谢谢
这是 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
任何人都可以分享任何 Python 服务器和客户端代码来演示在 gRPC 中使用类似于 https://jbrandhorst.com/post/grpc-binary-blob-stream/ 的分块吗?谢谢
这是 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