浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

beezari: Chunked decoding in python

Chunked decoding in python

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

posted on 2012-03-19 00:20  lexus  阅读(482)  评论(0编辑  收藏  举报