处理返回的 Protocol Buffer 文件

Dealing with returned Protocol Buffer Files

我正在向 API 发送 get 请求以找出 Public 运输实时位置。在他们的文档中,他们声明 returns 两个协议缓冲区文件。

问题是,我在 python 中编程,找不到任何关于如何处理这些返回文件的资源。我在网上搜索的关于协议缓冲区文件的大部分信息都是如何创建一个(序列化)。

是否有示例代码显示如何处理(反序列化?)返回的包含协议缓冲区文件的获取请求?

抱歉,如果我误解或使用了不正确的术语,请告诉我!

Here 是我能找到的唯一一份阐明它 returns 两个协议文件和返回内容的结构(?)的文档

Protobuf 不是自描述协议。发布 API 的人也应该发布架构定义(通常是 .proto 文件),您可以 运行 通过现成的工具。向他们询问架构文件(注意:他们还需要告诉您根消息类型是什么)。

请注意,可以从原始有效负载对架构进行逆向工程,但这很耗时,需要了解数据的外观(许多字段可以以多种不同的方式解释,给出不同的结果——你需要知道哪个是 "right"),并且失去所有语义(名称等)。如果你能得到 .proto,所有这一切都可以避免。如果你不能...我也许可以帮助一些。

第 3.1.1 章。您的 linked 文档声明数据符合 Google 发布的参考,包括相关页面的 link。该页面包含数据的 .proto 定义。

3.1.1 GTFS Compliance

The GTFS bundle is compliant with the specification reference published by google on 3 February 2016. The GTFS real time feed is also compliant with the GTFS reference published by google on 26 February 2015. The references for both feed components specifications can be found at the following URLs:

从网站下载 gtfs-realtime.proto 文件并使用 protoc --python_out=. gtfs-realtime.proto 编译它。这将创建一个 gtfs_realtime_pb2.py,您可以像这样使用它:

import requests
import gtfs_realtime_pb2

api_key = "<Your API key>"

session = requests.Session()
session.headers.update({"Authorization": "apikey " + api_key})
response = session.get("https://api.transport.nsw.gov.au/v1/gtfs/vehiclepos/nswtrains")
message = gtfs_realtime_pb2.FeedMessage()
message.ParseFromString(response.content)
print(message)

对于这样的输出

header {
  gtfs_realtime_version: "1.0"
  incrementality: FULL_DATASET
  timestamp: 1575847311
}
entity {
  id: "1"
  vehicle {
    trip {
      trip_id: "165.011219.127.0840"
      schedule_relationship: SCHEDULED
      route_id: "4T.C.165"
    }
    position {
      latitude: -28.636098861694336
      longitude: 153.54798889160156
      bearing: 273.8424072265625
    }
    timestamp: 1575847282
    congestion_level: UNKNOWN_CONGESTION_LEVEL
    stop_id: "24811"
    vehicle {
      id: "165"
      label: "08:40am (165)  Casino - Tweed Heads"
    }
  }
}
entity {
  id: "2"
...