motor.web - Integrate Motor with the Tornado web framework

class motor.web.GridFSHandler(application, request, **kwargs)

A handler that can serve content from GridFS, very similar to tornado.web.StaticFileHandler.

db = motor.MotorClient().my_database
application = web.Application([
    (r"/static/(.*)", web.GridFSHandler, {"database": db}),

By default, requests’ If-Modified-Since headers are honored, but no specific cache-control timeout is sent to clients. Thus each request for a GridFS file requires a quick check of the file’s uploadDate in MongoDB. Override get_cache_time() in a subclass to customize this.

get_cache_time(path, modified, mime_type)

Override to customize cache control behavior.

Return a positive number of seconds to trigger aggressive caching or 0 to mark resource as cacheable, only. 0 is the default.

get_gridfs_file(bucket, filename, request)

Overridable method to choose a GridFS file to serve at a URL.

By default, if a URL pattern like "/static/(.*)" is mapped to this GridFSHandler, then the trailing portion of the URL is used as the filename, so a request for “/static/image.png” results in a call to MotorGridFSBucket.open_download_stream_by_name() with “image.png” as the filename argument. To customize the mapping of path to GridFS file, override get_gridfs_file and return a Future MotorGridOut from it.

For example, to retrieve the file by _id instead of filename:

class CustomGridFSHandler(motor.web.GridFSHandler):
    def get_gridfs_file(self, bucket, filename, request):
        # Path is interpreted as _id instead of name.
        # Return a Future MotorGridOut.
        return fs.open_download_stream(file_id=ObjectId(path))

Changed in version 1.0: BREAKING CHANGE: Now takes a MotorGridFSBucket, not a MotorGridFS. Also takes an additional request parameter.

Changed in version 0.2: get_gridfs_file no longer accepts a callback, instead returns a Future.

set_extra_headers(path, gridout)

For subclass to add extra headers to the response