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):
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)