哈哈。pb是个好东西。用http请求,则更棒棒。直接上代码:
async def call_proto_http(url, req):
try:
data = req.SerializeToString()
length = len(data)
except Exception as e:
pass
headers = {'Content-type': 'application/x-protobuf',
'Content-Length': str(length)}
async with aiohttp.ClientSession() as session:
async with session.post(url, timeout=10, data=data, headers=headers) as response:
# logging.debug('post_json url {}, data {}'.format(url, data))
status = response.status
content = await response.read()
logging.debug(
"call_proto_http url:{}, status:{}, content:{}".format(url, status, content))
return status, content
async def test_upload_file(file_name, file_bytes):
f = FileDataRequest() # 这个是pb对象
f.FileName = file_name
f.FilePath = ""
f.FileContent = file_bytes
f.FileMd5 = ""
url = "http://127.0.0.1:3001/Upload"
status, content = await call_proto_http(url, f)
rsp = FileDataResponse()
rsp.ParseFromString(content) # 返回的content用另外一个Pb对象反序列化,完美
return rsp.Code, rsp.ErrMsg, rsp.FilePat