Python的请求 - 分块流

问题描述:

由于故障服务器的设计,我不得不流下来JSON,如果我找到一个纠正一个空字节。我正在使用python requests来做到这一点。每个JSON事件由\n分隔。我在这里试图做的是拉下一块(总是小于一个日志行)。通过该块搜索事件能指结束符("\"status\":\d+\d+\d+}}\n")。Python的请求 - 分块流

如果那个指示符在那里,我会用完整的JSON事件做一些事情,如果不是的话,我把这个块添加到缓冲区中,然后抓住下一个块并寻找标识符。只要我把它弄下来,我会开始搜索空字节。

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

对于初学者来说,什么是'\ d + \ d + \ d +'的意义 - 这是'\ d +'在某种程度上打破一些正则表达式引擎掩饰。 – zwer

首先,该正则表达式是搞砸\d+的意思是“一个或多个数字”他们为什么链三个人在一起?此外,您还需要使用“原始字符串”对于这种作为\的模式被视为转义字符让你的模式没有得到适当的建造。你想要将其更改为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... 

它看起来复杂,但它实际上是,如果很容易你读它一行行,你就会有(在同一块来考虑潜在的多个事件的分隔符)做一些复杂(重叠比赛和这样)用正则表达式匹配,太。

+0

哇。这是我收到的最全面的答案。希望我能给你更多的分数! – HectorOfTroy407