Skip to content

Instantly share code, notes, and snippets.

@joshmarshall
Created March 15, 2011 02:35
Show Gist options
  • Save joshmarshall/870216 to your computer and use it in GitHub Desktop.
Save joshmarshall/870216 to your computer and use it in GitHub Desktop.
Temporary File PUT Transfer Handler for Tornado
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.httputil
import tempfile
class MainHandler(tornado.web.RequestHandler):
def put(self):
filename = self.request.body.name
# do stuff with the image
self.write("The image file is %s" % filename)
self.request.body.close()
class TestImageHandler(tornado.httpserver.HTTPParseBody):
content_left = 0
def __call__(self):
self.content_left = self.content_length
self.temporary_fp = tempfile.NamedTemporaryFile()
self.read_chunk()
def read_chunk(self):
buffer_size = 4096
if self.content_left < buffer_size:
buffer_size = self.content_left
self.stream.read_bytes(buffer_size, self.data_callback)
def data_callback(self, data=None):
self.content_left -= len(data)
self.temporary_fp.write(data)
if self.content_left > 0:
tornado.ioloop.IOLoop.instance().add_callback(self.read_chunk)
else:
self.request.body = self.temporary_fp
self.temporary_fp.flush()
self.temporary_fp.seek(0)
self.done()
application = tornado.web.Application([
(r"/", MainHandler),
])
body_handlers = [
("image/.+", TestImageHandler),
]
if __name__ == "__main__":
application.listen(8888, body_handlers=body_handlers)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment