1. 環(huán)境配置
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; //頁條目數(shù)
}
3. 使用protoc把配置文件轉成python代碼
protoc --python_out=. ./test.proto
注:protoc配置到環(huán)境變量
然后當前目錄下會生成與.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。SerializeToString 和 ParseFromString,分別對應的是序列化和反序列化。
5. 編寫python腳本測試協(xié)議
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實現(xiàn) 一文,將大佬的Flask改用FastAPI實現(xiàn)