Protobuf示例:Golang and Python

之前的文章中已经展示过如何在C++中使用protobuf,本文将简单示范protobuf在GolangPython中的使用。

Talk is cheap. Show you my code.

首先是Python:

import addressbook_pb2
import random
import uuid


def Home():
    return addressbook_pb2.Person.HOME


def Work():
    return addressbook_pb2.Person.WORK


def Mobile():
    return addressbook_pb2.Person.MOBILE


switch = {0: Mobile(), 1: Home(), 2: Work()}

# from protobuf to string


def Write2AB(addressbook):
    for i in range(20):
        person = addressbook.people.add()
        person.id = i
        person.name = 'name: ' + str(i)
        person.email = str(i) + '@eamil.com'

        phone = person.phones.add()
        phone.type = switch[random.randint(0, 999) % 3]
        phone.number = str(uuid.uuid1())

    return addressbook.SerializeToString()


def ReadFromAB(addressbook):
    i = 1
    for people in addressbook.people:
        print('\n======  {} ======'.format(i))
        print('Person ID: ', people.id)
        print('Person Name: ', people.name)
        print('Person Email: ', people.email)

        print('Person PhoneNumber:')
        for phone in people.phones:
            if phone.type == addressbook_pb2.Person.MOBILE:
                print('\t type:Mobile number:{}'.format(phone.number))
            elif phone.type == addressbook_pb2.Person.HOME:
                print('\t type:Home number:{}'.format(phone.number))
            if phone.type == addressbook_pb2.Person.WORK:
                print('\t type:work number:{}'.format(phone.number))
        i += 1


if __name__ == "__main__":
    ab = addressbook_pb2.AddressBook()
    abString = Write2AB(ab)
    print(abString)

    # from string to protobuf
    ab.ParseFromString(abString)
    ReadFromAB(ab)

接下来是Golang:

package main

import (
	"fmt"
	"strconv"

	uuid "github.com/satori/go.uuid"

	"github.com/golang/protobuf/proto"
	"github.com/zj/tutorial"
)

// Write2AB return []byte from protobuf
func Write2AB(ab *tutorial.AddressBook) ([]byte, error) {
	for i := 0; i < 10; i++ {
		person := &tutorial.Person{}
		person.Id = int32(i)
		person.Name = "name" + strconv.Itoa(i)
		person.Email = strconv.Itoa(i) + "@email.com"

		phone := &tutorial.Person_PhoneNumber{}
		switch i % 3 {
		case 0:
			phone.Type = tutorial.Person_MOBILE
		case 2:
			phone.Type = tutorial.Person_WORK
		default:
			phone.Type = tutorial.Person_HOME
		}
		phone.Number = uuid.Must(uuid.NewV4()).String()

		person.Phones = append(person.Phones, phone)

		ab.People = append(ab.People, person)
	}

	return proto.Marshal(ab)

}

// ReadFromBytes read addressbook from []byte
func ReadFromBytes(abByte []byte) (*tutorial.AddressBook, error) {
	ab := &tutorial.AddressBook{}
	err := proto.Unmarshal(abByte, ab)
	if err != nil {
		return nil, err
	}
	return ab, nil
}

func main() {
	ab := &tutorial.AddressBook{}

	abBytes, err := Write2AB(ab)
	if err != nil {
		fmt.Println(err)
		return
	}

	ab, err = ReadFromBytes(abBytes)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ab)
}

本文采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。

posted @ 2020-04-30 16:05  落雷  阅读(427)  评论(0编辑  收藏  举报