利用protobuf格式进行前后端数据传输

本文介绍了如何利用protobuf格式进行前后端数据传输。在后端,通过protoc将.proto文件转换为Python代码,设置对象并序列化。前端则使用protobuf.js加载.proto文件并反序列化接收到的数据。
摘要由CSDN通过智能技术生成

创建student.proto文件,格式如下:

  1 syntax = "proto3";
  2 message Student{
  3     int64 id = 1;
  4     string name = 2;
  5     int64 age = 3;
  6 }
 

后端用python:

    通过protoc将.proto文件生成XX_pb2.py文件,然后import使用,在后端对.proto文件中变量进行赋值,然后对数据进行序列化SerializeToString(): serializes the message and returns it as a string. Note that the bytes are binary, not text; we only use the str type as a convenient container.

     生成命令:protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/XXX.proto

     创建对象:student = student_pb2.Student()

     为对象的各个变量赋值:

     def set_student():
        student.id = 8
        student.name = 'Sally'
        student.age = 17

    student = student_pb2.Student()

    st

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值