gridfs – Tools for working with GridFS

GridFS is a specification for storing large objects in Mongo.

The gridfs package is an implementation of GridFS on top of pymongo, exposing a file-like interface.

See general MongoDB documentation

gridfs

class gridfs.GridFS(database, collection='fs')

Create a new instance of GridFS.

Raises TypeError if database is not an instance of Database.

Parameters:
  • database: database to use
  • collection (optional): root collection to use

New in version 1.6: The collection parameter.

See general MongoDB documentation

gridfs

delete(file_id)

Delete a file from GridFS by "_id".

Removes all data belonging to the file with "_id": file_id.

Warning

Any processes/threads reading from the file while this method is executing will likely see an invalid/corrupt file. Care should be taken to avoid concurrent reads to a file while it is being deleted.

Parameters:
  • file_id: "_id" of the file to delete

New in version 1.6.

get(file_id)

Get a file from GridFS by "_id".

Returns an instance of GridOut, which provides a file-like interface for reading.

Parameters:
  • file_id: "_id" of the file to get

New in version 1.6.

get_last_version(filename)

Get a file from GridFS by "filename".

Returns the most recently uploaded file in GridFS with the name filename as an instance of GridOut. Raises NoFile if no such file exists.

An index on {filename: 1, uploadDate: -1} will automatically be created when this method is called the first time.

Parameters:
  • filename: "filename" of the file to get

New in version 1.6.

list()

List the names of all files stored in this instance of GridFS.

Changed in version 1.6: Removed the collection argument.

new_file(**kwargs)

Create a new file in GridFS.

Returns a new GridIn instance to which data can be written. Any keyword arguments will be passed through to GridIn().

Parameters:
  • **kwargs (optional): keyword arguments for file creation

New in version 1.6.

open(*args, **kwargs)

No longer supported.

Changed in version 1.6: The open method is no longer supported.

put(data, **kwargs)

Put data in GridFS as a new file.

Equivalent to doing:

>>> f = new_file(**kwargs)
>>> try:
>>>     f.write(data)
>>> finally:
>>>     f.close()

data can be either an instance of str or a file-like object providing a read() method. Any keyword arguments will be passed through to the created file - see GridIn() for possible arguments. Returns the "_id" of the created file.

Parameters:
  • data: data to be written as a file.
  • **kwargs (optional): keyword arguments for file creation

New in version 1.6.

remove(*args, **kwargs)

No longer supported.

Changed in version 1.6: The remove method is no longer supported.

Sub-modules:

Previous topic

cursor_manager – Managers to handle when cursors are killed after being closed

Next topic

errors – Exceptions raised by the gridfs package

This Page