【问题标题】:Iterating on HTTP API data from source从源中迭代 HTTP API 数据
【发布时间】:2018-07-25 00:11:10
【问题描述】:

我正在使用 python urllib 从 HTTP API 读取数据,如下所示:

response = urllib.request.urlopen(url)
stations = json.loads(response.read().decode())
for station in stations:
    producer.send("test", json.dumps(station).encode())

我注意到,在应用读取函数时,数据首先转换为字节类型。然后,它存储在一个列表(站)中,我将对其进行迭代。

由于我正在处理非常大的 HTTP 响应,因此我需要直接从 HTTP API 迭代数据,而无需将其中间存储在我的磁盘或 RAM 中。是否有可能在 Python 中处理这种需求?

我也想知道这个 Java 示例代码是否可以解决我的问题:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL(url);
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            producer.send("test", inputLine)
        in.close();
    }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java python api http


    【解决方案1】:

    Python Requests 库支持 Streaming Requests。这允许您读取每行的响应,而无需将整个响应存储在内存中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多