用 Python 學 Google Protocol Buffers - Part 2

Posted on  Nov 3, 2018  in  Python 程式設計 - 高階  by  Amo Chen  ‐ 3 min read

本文為系列教學:

上篇文章介紹 Google Protocols Buffers (proto3) 與 Python 的基本使用方法,本篇將進一步介紹幾個 proto3 重要語法與特性。

proto3 沒有 required 關鍵字

談到 proto3 一定要知道的事,就是 proto3 沒有 required 關鍵字。

只有在 proto2 的語法中,可以用 required 關鍵字表示一個欄位(field)必須是不可或缺的存在:

syntax = 'proto2';

message MyMessage {
	required string id = 1;
}

不過 proto3 拿掉 required 關鍵字,因此在 proto3 中所有的欄位(field)都是選擇性的,所以 1 個 message 某些欄位(field)缺值的話,也照樣能夠轉成 binary 。

repeated 關鍵字

如果 1 個欄位能夠以 Python 的 list, tulple 對應的話,那麼該欄位就需要 repeated 關鍵字,譬如 1 個使用者(User)可能有多支電話號碼,就可以用 repeated 如此表達:

syntax = 'proto3';

message User {
	repeated string phonenumbers = 1;
}

編譯成 Python 程式碼之後,就能夠使用 extend 方式一次指定多個電話號碼:

>>> from user_pb2 import User
>>> user = User()
>>> user.phonenumbers.extend(['phone1', 'phone2'])
>>> user.SerializeToString()
b'\n\x06phone1\n\x06phone2'

或者使用 append 附加 1 支電話號碼:

>>> user.phonenumbers.append('phone3')
>>> user.phonenumbers
['phone1', 'phone2', 'phone3']

不過需注意的是, repeated 並沒有規定必須至少 1 個值在欄位中, 0 個也是合法的,如果有個數限制的話,那麼在指定給 Google Protocol Buffers 的 Message 之前就需要自行檢查。此外, list, tuple 裡的順序在 Message 內也都會保留。

repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

保留欄位(Reserved Fields)

由於 message 的欄位可能會隨著應用程式的演化有增有減,如果 .proto 檔都一直保持在最新,而且編譯的程式碼都有更新的情況下,就不太需要擔心這個問題。但如果有些系統忘記更新或尚未更新完成,在這情況下,如果某些新增的欄位用的是先前刪去的欄位編號時,就會造成誤用。

例如以下範例, UserV2 的欄位 1 是 devices (1 個使用者可能多個裝置),而 UserV1 的欄位 1 則是 phonenumbers ,可以發現 UserV1 其實還是可以正常讀取 UserV2 的 binary 資料,只是欄位資料並不是我們預期的:

syntax = 'proto3';

message UserV1 {
	repeated string phonenumbers = 1;
}

message UserV2 {
	repeated string devices  = 1;
}
>>> import user_pb2
>>> user_v2 = user_pb2.UserV2()
>>> user_v2.devices.extend(['iPhone XS', 'Macbook Pro'])
>>> user_v2_bytes = user_v2.SerializeToString()
>>>
>>> user_v1 = user_pb2.UserV1.FromString(user_v2_bytes)
>>> user_v1.phonenumbers
['iPhone XS', 'Macbook Pro']

上述情況就是不同版本卻共用相同欄位編號造成的誤用,為了避免這種情況, Google Protocols Buffers 提供保留欄位編號的功能,如果刪去某些欄位時,可以用 reserved 關鍵字保留該欄位編號,避免未來被誤用。

範例:

syntax = 'proto3';

message UserV2 {
	reserved 1;
	repeated devices = 2;
}

reserved 除了能保留欄位編號之外,也支援欄位名稱:

message UserV2 {
	reserved 1;
	reserved "phonenumbers";
	repeated devices = 2;
}

詳細用法可以參閱 Google Protocol Buffers 文件。

列舉(Enumerations)

Google Protocol Buffers 也提供列舉的功能,可以用 enum 關鍵字定義列舉,例如:

message User {
	enum Sex {
		UNKNOWN = 0;
		MALE = 1;
		FEMALE = 2;
	}
	Sex sex = 1;
	string name = 2;
}
>>> import user_pb2
>>> user = user_pb2.User()
>>> user.sex
0

上述使用 enum 可以發現 sex 欄位預設為 0 ,這是由於 Google Protocol Buffers 規定 enum 的 0 會被設定為預設值,也由於如此,所有的 enum 都會從 0 開始設定值,而且 0 也必須排在第 1 個,如果不是從 0 開始,就會發生類似以下的錯誤:

user.proto: The first enum value must be zero in proto3.

小結

至此,我們已認識幾個重要的 proto3 關鍵字與特性,下一篇將介紹如何定義更複雜的 .proto 以及如何用 Python 操作它。

References

https://developers.google.com/protocol-buffers/docs/proto3

對抗久坐職業傷害

研究指出每天增加 2 小時坐著的時間,會增加大腸癌、心臟疾病、肺癌的風險,也造成肩頸、腰背疼痛等常見問題。

然而對抗這些問題,卻只需要工作時定期休息跟伸展身體即可!

你想輕鬆改變現狀嗎?試試看我們的 PomodoRoll 番茄鐘吧! PomodoRoll 番茄鐘會根據你所設定的專注時間,定期建議你 1 項辦公族適用的伸展運動,幫助你打敗久坐所帶來的傷害!

追蹤新知

看完這篇文章了嗎?還意猶未盡的話,追蹤粉絲專頁吧!

我們每天至少分享 1 篇文章/新聞或者實用的軟體/工具,讓你輕鬆增廣見聞提升專業能力!如果你喜歡我們的文章,或是想了解更多特定主題的教學,歡迎到我們的粉絲專頁按讚、留言讓我們知道。你的鼓勵,是我們的原力!

贊助我們的創作

看完這篇文章了嗎? 休息一下,喝杯咖啡吧!

如果你覺得 MyApollo 有讓你獲得實用的資訊,希望能看到更多的技術分享,邀請你贊助我們一杯咖啡,讓我們有更多的動力與精力繼續提供高品質的文章,感謝你的支持!