FastAPI实现Protobuf服务端

2021-11-04  本文已影响0人  还是那个没头脑

1. 环境配置

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

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

1.4 pycharm安装protobuf插件

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

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文件。


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()

谢鸣

感谢 @风中的承诺 大佬的 Protobuf后台python实现 一文,将大佬的Flask改用FastAPI实现

上一篇 下一篇

猜你喜欢

热点阅读