protobuf-python

2020-11-15  本文已影响0人  Hmcf
安装protobuf环境
编写protobuf文件
// test.proto
syntax = "proto3";

message say_hello {
    string name = 1;
    int32 age = 2;
}
// 对应的嵌套结构、数组等可设置对应的关键字配置
根据test.proto文件生成python文件

protoc --python_out=./ test.proto

编写python服务和客户端使用
"""
Author: lxcos
Date: 2020-11-11 16:42:12
"""

import protoconf_pb2 as pb2
from flask import Flask


# 从给出的字符串中解析一条message
# sh.ParseFromString(msg)
# print(sh)

# print(f'name {sh.name}, {sh.age}')
app = Flask(__name__)


@app.route('/')
def index():
    sh = pb2.say_hello()
    sh.name = "chen"
    sh.age = 23

    # 序列化这个message和以字符串的方式返回。 注意,这是二进行字节,不是一个文本; 我们只使用str类型作为一个方便的容器。
    msg = sh.SerializeToString()
    # print(msg)
    return msg


if __name__ == '__main__':
    app.debug = True  # 设置调试模式,生产模式的时候要关掉debug
    app.run()
# encoding: utf-8
"""
Author: lxcos
Date: 2020-11-11 16:42:12
"""

import requests
import protoconf_pb2 as pb2

msg = requests.get("http://127.0.0.1:5000/")

sh = pb2.say_hello()
sh.ParseFromString(msg.content)

print(sh.name, sh.age)
上一篇 下一篇

猜你喜欢

热点阅读