Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tornado import ioloop, web
- from cStringIO import StringIO
- import functools
- class ChunkedHandler(web.RequestHandler):
- def post(self):
- # we assume that the wrapping server has not sent/flushed the
- # 100 (Continue) response
- if self.request.headers.get('Expect', None) == '100-continue' and \
- not 'Content-Length' in self.request.headers and \
- self.request.headers.get('Transfer-Encoding', None) == 'chunked':
- self._auto_finish = False
- self.chunks = StringIO()
- self._stream = self.request.connection.stream
- # cache callback proxies
- self._length_callback = lambda: \
- self._stream.read_until('\r\n', self._on_chunk_length)
- self._data_callback = lambda len: \
- lambda: self._stream.read_bytes(len + 2, self._on_chunk_data)
- self._stream.io_loop.add_callback(self._length_callback)
- self.request.write("HTTP/1.1 100 (Continue)\r\n\r\n")
- else:
- raise web.HTTPError(500, "non-chunked request")
- def _on_chunks(self, all_chunks):
- self.finish()
- print "got all chunks, total size=%d" % all_chunks.tell()
- def _on_chunk_length(self, data):
- assert data[-2:] == '\r\n', "chunk size ends with CRLF"
- chunk_length = int(data[:-2], 16)
- if chunk_length:
- self._stream.io_loop.add_callback(self._data_callback(chunk_length))
- else:
- self._on_chunks(self.chunks)
- def _on_chunk_data(self, data):
- assert data[-2:] == '\r\n', "chunk data ends with CRLF"
- self.chunks.write(data[:-2])
- self._stream.io_loop.add_callback(self._length_callback)
Add Comment
Please, Sign In to add comment