【问题标题】:What is the best way to combine multiple ndjson urls from a REST API?从 REST API 组合多个 ndjson url 的最佳方法是什么?
【发布时间】:2022-12-24 22:57:29
【问题描述】:

我的目标是提取所有 url 并向每个 ndjson 文件添加一个获取请求;但是,当有 10 个以上的 url 时,这可能会很复杂。有没有更好的方法来执行此操作,或者我是否需要放入多个 GET 请求,然后加入 ndjson 文件,然后解析数据。

print(response.text)

输出:

{"transactionTime":"2022-03-27T08:51:32.174-04:00","request":"https://api.site/data/5555/$export","requiresAccessToken":true,"output": [
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838916.ndjson"
        },
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838917.ndjson"
        },
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838918.ndjson"
        }
    ]
"error":[],"JobID":12443}

list(response.text.values())

输出:


 [
    "1990-01-28T08:51:32.174-04:00",
    "https://api.site/data/5555/$export",
    true,
    [
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838916.ndjson"
        },
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838917.ndjson"
        },
        {
            "type":"robot",
            "url":"https://api.site/data/5555/838918.ndjson"
        }
    ]

我目前在这里添加多个 GET 请求:

response1 = requests.get("https://api.site/data/5555/838916.ndjson",headers=headers)
response2 = requests.get("https://api.site/data/5555/838917.ndjson",headers=headers)
response3 = requests.get("https://api.site/data/5555/838918.ndjson",headers=headers)

【问题讨论】:

  • 代码 response.text.values() 看起来与我使用过的任何 python 模块都不相似。通常 response.text 返回没有 .values() 方法的 str
  • 我更新以尝试进一步解释。

标签: python python-requests


【解决方案1】:

如果我正确理解你的问题,你发送一些返回你提供的 JSON 对象的请求。您需要从该对象向每个 url 发送请求,并将数据合并到一个容器中(例如 dict)。

from requests import Session

headers = { ... }  # some headers

sess = Session()
sess.headers.update(headers)

resp = sess.get("https://api.site/data/5555/$export")
for item in resp.json()["output"]:
    ndjson = sess.get(item["url"])
    # here some code to process ndjson.text

通常情况下ndjson是一个由换行符分隔的 JSON 对象列表,因此如果没有实际数据,就无法帮助代码以正确的(以供将来解析)格式存储此数据。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    相关资源
    最近更新 更多