?

Log in

No account? Create an account
Chunked decoding in python - 豬頭'blog — LiveJournal [entries|archive|friends|userinfo]
豬頭

[ website | 豬頭基 ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Links
[Links:| o0o blog myspace deviantart PromoDJ KTK project ]

Chunked decoding in python [Mar. 15th, 2011|05:07 pm]
豬頭
[Tags|, ]

I haven't been able to find any short and quick method of decoding "chunked-encoding" encoded data in python without whacking 3rd party libraries, so here is my bet:
(chunked content encoding explained here: http://www.faqs.org/rfcs/rfc2616.html)

assuming that data contains raw http response. Code simplified for readability
def decode_chunked(data):
    offset = 0
    encdata = ''
    newdata = ''
    offset = string.index(data, "\r\n\r\n") + 4 # get the offset 
    # of the data payload. you can also parse content-length header as well.
    encdata =data[offset:]
    try:
        while (encdata != ''):
            off = int(encdata[:string.index(encdata,"\r\n")],16)
            if off == 0:
                break
            encdata = encdata[string.index(encdata,"\r\n") + 2:]
            newdata = "%s%s" % (newdata, encdata[:off])
            encdata = encdata[off+2:]
                             
    except:
       line = traceback.format_exc()
       print "Exception! %s" %line # probably indexes are wrong
    return newdata


for php version look here:

http://www.codingforums.com/showthread.php?t=147061
LinkReply