Python:限制发布到s的json字符串的大小

2024-10-01 11:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在向一个最大数据上传限制为1MB的服务器发布数十万条JSON记录。我的记录可以是非常可变的大小,从几百字节到几十万字节不等。在

def checkSize(payload):
    return len(payload) >= bytesPerMB 


toSend = []
for row in rows:
    toSend.append(row)
    postData = json.dumps(toSend)
    tooBig = tooBig or checkSize()
    if tooBig:
          sendToServer(postData)

然后发送到服务器。它目前是有效的,但是不断地将toSend转储到jsonified字符串似乎非常沉重,而且几乎100%过多,尽管我似乎找不到另一种方法。我可以把每个新记录串起来,并记录下它们将在一起的记录吗?在

我肯定有更干净的方法来做这件事,但我就是不知道。在

谢谢你的帮助。在


这是我现在使用的答案,我是在@rsegal下面同时提出的,只是为了清晰和完整而发布的(sendToServer只是一个显示一切正常工作的虚拟函数)

^{pr2}$

Tags: 数据方法服务器jsonreturn字节def记录
1条回答
网友
1楼 · 发布于 2024-10-01 11:31:50

我会做如下的事情:

toSend = []
toSendLength = 0
for row in rows:
    tentativeLength = len(json.dumps(row))
    if tentativeLength > bytesPerMB:
        parsingBehavior // do something about lolhuge files
    elif toSendLength + tentativeLength > bytesPerMB: // it would be too large
        sendToServer(json.dumps(toSend)) // don\'t exceed limit; send now
        toSend = [row] // refresh for next round - and we know it fits!
        toSendLength = tentativeLength
    else: // otherwise, it wont be too long, so add it in
        toSend.append(row)
        toSendLength += tentative
sentToServer(json.dumps(toSend)) // if it finishes below the limit

你的解决方案的问题是,从大公司的角度来看,它不是很好。我的是线性时间,你的是二次时间,因为你要检查每个循环的累计长度。每次重置postData也不是很有效。在

相关问题 更多 >