在使用Python 搭建gprc框架时,遇到传输文件大小限制,异常信息如下:
Traceback (most recent call last):
File "/grpc_demo/demo_client.py", line 47, in <module>
run("localhost:18991", ".")
File "/grpc_demo/demo_client.py", line 29, in run
response = stub.CreateFile(demo_pb2.FileRequest(file=data, name='ffile.jpg'.encode('utf-8'), rpath=rpath.encode('utf-8')))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.RESOURCE_EXHAUSTED
details = "Received message larger than max (5009675 vs. 4194304)"
debug_error_string = "{"created":"@1593481044.082878000","description":"Error received from peer ipv6:[::1]:18991","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"Received message larger than max (5009675 vs. 4194304)","grpc_status":8}"
>
这是因为grpc默认传输文件大小为4*1024*1024 也就是4兆,超出此大小便会抛出StatusCode.RESOURCE_EXHAUSTED这个异常,解决此问题需要修改默认传输大小限制。查阅各种资料,发现大多为golang版本的解决方案,经过摸索测试,发现如下解决方案:
在server创建时添加options参数:
MAX_MESSAGE_LENGTH = 256*1024*1024 # 可根据具体需求设置,此处设为256M
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=[
('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH),
]
)
只需将服务端设置便可。