Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Created July 28, 2014 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drgarcia1986/a7088afd35349fe7a458 to your computer and use it in GitHub Desktop.
Save drgarcia1986/a7088afd35349fe7a458 to your computer and use it in GitHub Desktop.
Image server with Python (Tornado) and MongoDB
# !/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Diego Garcia'
import tornado.ioloop
import tornado.web
from bson.json_util import dumps
from pymongo import Connection
from bson.objectid import ObjectId
from gridfs import GridFS
class ImageHandler(tornado.web.RequestHandler):
def initialize(self):
self.fs = GridFS(Connection()['database'], 'imgs')
def get(self, img_id):
image = self.fs.get(ObjectId(img_id))
self.set_header('Content-type', image.content_type)
self.set_header('Content-length', image.length)
self.write(image.read())
self.finish()
def post(self):
image = self.request.files['files'][0]['body']
tipo = self.request.headers['Content-Type']
img_id = self.fs.put(image, content_type=tipo)
self.write(dumps({"img_id": img_id}))
self.finish()
application = tornado.web.Application([
(r"/img/?", ImageHandler),
(r"/img/([^/]+)?", ImageHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment