前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python: 使用http方式调用pb协议

python: 使用http方式调用pb协议

作者头像
超级大猪
发布2019-11-21 23:58:13
2.9K0
发布2019-11-21 23:58:13
举报
文章被收录于专栏:大猪的笔记

哈哈。pb是个好东西。用http请求,则更棒棒。直接上代码:

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-09-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档