如何在 Python 中读取应用程序/八位字节流

问题描述

基于 this question 构建,我使用 Python 脚本调用以下链接中详述的 API:

https://developer.wmata.com/docs/services/gtfs/operations/5cdc51ea7a6be320cab064fe?

我使用下面的代码调用api:

import requests

# define functions
def _prepare_url(path):
    return f'{API_URL}/{path.lstrip("/")}'


def pull_data(path,params=None,headers=None):
    url =_prepare_url(path)
    return requests.get(url,params=params,headers=headers)


# print results in cleaner format
def jprint(obj):
    # create a formatted string of the Python JSON object
    text = json.dumps(obj,sort_keys=True,indent=4)
    print(text)


API_URL = 'https://api.wmata.com'

# authenticate with your api key
headers = {
    "api_key": "myKey",}

response = pull_data('/gtfs/bus-gtfsrt-tripupdates.pb',headers=headers)
print(response.content)
print(response.headers)
print(response.url)

但它返回一个无意义的数据流以及以下标头:

Request-Context: appId=cid-v1:2833aead-1a1f-4ffd-874e-ef3a5ceb1de8
Cache-Control: public,must-revalidate,max-age=5
Date: Thu,11 Feb 2021 22:05:31 GMT
ETag: 0x8D8CED90CC8419C
Content-Length: 625753
Content-MD5: fspEFl7LJ8QbZPgf677WqQ==
Content-Type: application/octet-stream
Expires: Thu,11 Feb 2021 22:05:37 GMT
Last-Modified: Thu,11 Feb 2021 22:04:49 GMT

'''b'\n\r\n\x031.0\x10\x00\x18\xd9\xef\xa5\x81\x06\x12\xee\x02\n\n1932817010\x1a\xdf\x02\n\x1a\n\n1932817010\x1a\x0820210214*\x0233\x12\x13\x08\x02\x1a\x06\x10\x9c\xff\xa5\x81\x06"\x0513752...'''

有关如何阅读此类回复的任何指导?

解决方法

GTFS-rt 以称为“protobuf”的压缩编码表示形式传输。您的 Python 脚本需要使用 gtfs-realtime.proto 文件(其中包含对 GTFS-rt 提要的预期内容的定义)以及 Google Protobuf Python 包,以便对响应进行解码。

以下是如何从文档中读取 GTFS-rt API 的示例:https://developers.google.com/transit/gtfs-realtime/examples/python-sample