FastAPI实现Protobuf服务端

1. 环境配置

1.1 安装python3
1.2 使用pip安装FastAPI和Protocbuf
pip3 install fastapi
pip3 install uvicorn
pip3 install protobuf
1.3 配置protoc

github下载对应和你PC对应版本的protoc。

img

1.4 pycharm安装protobuf插件

在plugins->Marketplace 搜索并安装 protobuf support 插件

img

2. .proto配置文件编写

syntax = "proto3";

message Response {
  int32 code = 1;

  message data {
    string id = 1;
    string title = 2;
  }

  repeated data dataList = 2;
}

message Request {
  string channelId = 1;  //频道id
  int32 page = 2;         //页码
  int32 pageSize = 3;     //页条目数
}

3. 使用protoc把配置文件转成python代码

protoc --python_out=. ./test.proto

注:protoc配置到环境变量

然后当前目录下会生成与.proto文件名相似的python文件。

img

4 编写FastAPI服务端

import uvicorn
from fastapi import FastAPI, Form
from fastapi import Response as fres
from test_pb2 import Request, Response

app = FastAPI()

@app.post('/protobuf')
async def _protobuf(pyload: bytes = Form(...)):
    # 解析请求
    req = Request()
    req.ParseFromString(pyload)
    print(req)

    # 编写响应
    res = Response()
    res.code = 200
    d1 = res.data()
    d1.id = "1"
    d1.title = "小明"
    d2 = res.data()
    d2.id = "2"
    d2.title = "李雷"
    res.dataList.append(d1)
    res.dataList.append(d2)
    print(res.SerializeToString())

    return fres(res.SerializeToString())

if __name__ == '__main__':
    uvicorn.run(
        app='main:app',
        host="0.0.0.0",
        port=8899,
        workers=4,
        reload=True,
        debug=True)

需重点记住这两个api。SerializeToStringParseFromString,分别对应的是序列化和反序列化。

5. 编写python脚本测试协议

import requests
from test_pb2 import Request, Response

def test_protobuf():
    """
    test
    :return:
    """
    req = Request()
    req.channelId = "people"
    req.page = 1
    req.pageSize = 10
    req_bytes = req.SerializeToString()
    data = {'pyload': req_bytes}
    response = requests.post("http://127.0.0.1:8899/protobuf", data=data)

    res = Response()
    res.ParseFromString(response.content)
    print(res)
    for i in res.dataList:
        print(i.title)


if __name__ == '__main__':
    test_protobuf()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值