【问题标题】:How to read application/octet-stream in Python如何在 Python 中读取应用程序/八位字节流
【发布时间】:2021-02-14 19:35:38
【问题描述】:

在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...'''

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

【问题讨论】:

    标签: python http python-requests byte gtfs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 2011-06-15
      • 2017-10-21
      相关资源
      最近更新 更多