Search code examples
pythoncherrypychunked-encoding

CherryPy How to Read Chunked Encoded Request Body


I try to get the data off POST body that has Transfer-Encoding: chunked header (doesn't have Content-Length). The content-type is application/octet-stream.

I tried

cherrypy.request.body.read()

But it froze and returned 500

I also tried

buffer = cherrypy.request.body.read(1024)

But doesn't know when to stop reading. Anyone has suggestion?


Solution

  • Here's the code I ended up using.

    def POST(self):
        f = open('tmp','wb')
        cherrypy.request.rfile.bufsize = 1024 * 1024 * 5  #adjust buffer size here
        while True:
            cherrypy.request.rfile._fetch();              #reading data
            if cherrypy.request.rfile.closed:             #end of stream checking
                break
            buffer = cherrypy.request.rfile.buffer        #your data is here
            cherrypy.request.rfile.buffer = ""            #clearing buffer
            f.write(buffer)                               #consume it
    
        f.close()
        return "done"