motor.web - Integrate Motor with the Tornado web framework¶
Warning
Motor will be deprecated on May 14th, 2026, one year after the production release of the PyMongo Async driver. Critical bug fixes will be made until May 14th, 2027. We strongly recommend that Motor users migrate to the PyMongo Async driver while Motor is still supported. To learn more, see the migration guide.
Utilities for using Motor with Tornado web applications.
- class motor.web.GridFSHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)¶
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
uploadDatein MongoDB. Overrideget_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 thisGridFSHandler, then the trailing portion of the URL is used as the filename, so a request for “/static/image.png” results in a call toMotorGridFSBucket.open_download_stream_by_name()with “image.png” as thefilenameargument. To customize the mapping of path to GridFS file, overrideget_gridfs_fileand return a FutureMotorGridOutfrom it.For example, to retrieve the file by
_idinstead 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))
- Parameters:
bucket: A
MotorGridFSBucketfilename: A string, the matched group of the URL pattern
request: An
tornado.httputil.HTTPServerRequest
Changed in version 1.0: BREAKING CHANGE: Now takes a
MotorGridFSBucket, not aMotorGridFS. Also takes an additionalrequestparameter.Changed in version 0.2:
get_gridfs_fileno longer accepts a callback, instead returns a Future.
- initialize(database, root_collection='fs')¶
- set_extra_headers(path, gridout)¶
For subclass to add extra headers to the response