Python请求 - Chunked Streaming

时间:2017-06-13 23:26:32

标签: python for-loop python-requests chunked-encoding

由于服务器设计错误,我必须流式传输JSON并在找到空字节时更正空字节。我使用python requests来执行此操作。每个JSON事件由\n分隔。我在这里尝试做的是拉下一个块(总是小于一个日志行)。在该块中搜索事件指示符("\"status\":\d+\d+\d+}}\n")的结尾。

如果那个能指标在那里我将用完整的JSON事件做一些事情,如果没有,我将该块添加到缓冲区b,然后抓住下一个块并查找标识符。一旦我解决了这个问题,我就会开始搜索空字节。

b = ""

for d in r.iter_content(chunk_size=25):

    s = re.search("\"status\":\d+\d+\d+}}\n", d)

    if s:
        d = d.split("\n", 1)
        fullLogLine = b + d[0]
        b = d[1]
    else:
        b = b + d

在这种情况下,我完全失去了b的价值。它似乎无法延续iter_content。每当我尝试打印b的值时,它就是空的。我觉得我在这里遗漏了一些明显的东西。一切都有帮助。感谢。

1 个答案:

答案 0 :(得分:2)

首先,正则表达式混乱\d+表示'一个或多个数字',那么为什么要将它们中的三个链接在一起呢?此外,您需要使用'raw string'作为此类型的模式,因为\被视为转义字符,因此您的模式无法正确构建。您想将其更改为re.search(r'"status":\d+}}', d)

其次,如果您的块中有两个换行符,则您的d.split()行可能会收到错误的\n

你甚至不需要正则表达式,好的'Python字符串搜索/切片足以确保你的分隔符正确:

logs = []  # store for our individual entries
buffer = []  # buffer for our partial chunks
for chunk in r.iter_content(chunk_size=25):  # read chunk-by-chunk...
    eoe = chunk.find("}}\n")  # seek the guaranteed event delimiter
    while eoe != -1:  # a potential delimiter found, let's dig deeper...
        value_index = chunk.rfind(":", 0, eoe)  # find the first column before it
        if eoe-1 >= value_index >= eoe-4:  # woo hoo, there are 1-3 characters between
            try:  # lets see if it's a digit...
                status_value = int(chunk[value_index+1:eoe])  # omg, we're getting there...
                if chunk[value_index-8:value_index] == '"status"':  # ding, ding, a match!
                    buffer.append(chunk[:eoe+2])  # buffer everything up to the delimiter
                    logs.append("".join(buffer))  # flatten the buffer and write it to logs
                    chunk = chunk[eoe + 3:]  # remove everything before the delimiter
                    eoe = 0  # reset search position
                    buffer = []  # reset our buffer
            except (ValueError, TypeError):  # close but no cigar, ignore
                pass  # let it slide...
        eoe = chunk.find("}}\n", eoe + 1)  # maybe there is another delimiter in the chunk...
    buffer.append(chunk)  # add the current chunk to buffer
if buffer and buffer[0] != "":  # there is still some data in the buffer
        logs.append("".join(buffer))  # add it, even if not complete...

# Do whatever you want with the `logs` list...

它看起来很复杂但是如果你逐行阅读它实际上很容易,你也必须使用正则表达式匹配来完成其中一些复杂性(重叠匹配等)(在同一块中考虑潜在的多事件分隔符。)