Guest User

Untitled

a guest
Jul 18th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. from tornado import ioloop, web
  2.  
  3. from cStringIO import StringIO
  4. import functools
  5.  
  6.  
  7. class ChunkedHandler(web.RequestHandler):
  8. def post(self):
  9. # we assume that the wrapping server has not sent/flushed the
  10. # 100 (Continue) response
  11. if self.request.headers.get('Expect', None) == '100-continue' and \
  12. not 'Content-Length' in self.request.headers and \
  13. self.request.headers.get('Transfer-Encoding', None) == 'chunked':
  14.  
  15. self._auto_finish = False
  16.  
  17. self.chunks = StringIO()
  18. self._stream = self.request.connection.stream
  19.  
  20. # cache callback proxies
  21. self._length_callback = lambda: \
  22. self._stream.read_until('\r\n', self._on_chunk_length)
  23. self._data_callback = lambda len: \
  24. lambda: self._stream.read_bytes(len + 2, self._on_chunk_data)
  25.  
  26. self._stream.io_loop.add_callback(self._length_callback)
  27.  
  28. self.request.write("HTTP/1.1 100 (Continue)\r\n\r\n")
  29. else:
  30. raise web.HTTPError(500, "non-chunked request")
  31.  
  32. def _on_chunks(self, all_chunks):
  33. self.finish()
  34. print "got all chunks, total size=%d" % all_chunks.tell()
  35.  
  36. def _on_chunk_length(self, data):
  37. assert data[-2:] == '\r\n', "chunk size ends with CRLF"
  38. chunk_length = int(data[:-2], 16)
  39.  
  40. if chunk_length:
  41. self._stream.io_loop.add_callback(self._data_callback(chunk_length))
  42. else:
  43. self._on_chunks(self.chunks)
  44.  
  45. def _on_chunk_data(self, data):
  46. assert data[-2:] == '\r\n', "chunk data ends with CRLF"
  47. self.chunks.write(data[:-2])
  48.  
  49. self._stream.io_loop.add_callback(self._length_callback)
Add Comment
Please, Sign In to add comment