Python: json string size limit for sending to server

I send hundreds of thousands of JSON records to a server with a maximum MAX data transfer size of 1 MB. My records can be very variable in size, from just a few hundred bytes to a few hundred thousand.

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)

which is then sent to the server. It currently works, but constantly dumping toSend in a jsonified string seems really hard and almost 100% too much, although I cannot find a way to do it differently. Can I be okay with a line of individual new entries and estimates that they will be together?

I'm sure there should be a cleaner way to do this, but I just don't know.

Thanks for any help provided.


, , , @rsegal , (sendToServer - , , ),

import pickle
import json

f = open("userProfiles")
rows = pickle.load(f)
f.close()

bytesPerMB = 1024 * 1024
comma = ","
appendSize = len(comma)

def sendToServer(obj):
    #send to server
    pass

def checkSize(numBytes):
    return numBytes >= bytesPerMB

def jsonDump(obj):
    return json.dumps(obj, separators=(comma, ":"))

leftover = []
numRows = len(rows)
rowsSent = 0

while len(rows) > 0:
    toSend = leftover[:]
    toSendSize = len( jsonDump(toSend) )
    leftover = []
    first = len(toSend) == 0

    while True:
        try:
            row = rows.pop()
        except IndexError:
            break

        rowSize = len( jsonDump(row) ) + (0 if first else appendSize)
        first = False

        if checkSize(toSendSize + rowSize):
            leftover.append(row)
            break

        toSend.append(row)
        toSendSize += rowSize

    rowsSent += len(toSend)
    postData = jsonDump(toSend)
    print "assuming to send '{0}' bytes, actual size '{1}'. rows sent {2}, total {3}".format(toSendSize, len(postData), rowsSent, numRows)
    sendToServer(postData)
+5
1

- :

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

, Big-O. , , . postData .

+2

All Articles