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 also
The MongoDB documentation on gridfs.
- class gridfs.GridFS(database: pymongo.database.Database, collection: str = 'fs')¶
Create a new instance of
GridFS
.Raises
TypeError
if database is not an instance ofDatabase
.- Parameters
database: database to use
collection (optional): root collection to use
Changed in version 4.0: Removed the disable_md5 parameter. See disable_md5 parameter is removed for details.
Changed in version 3.11: Running a GridFS operation in a transaction now always raises an error. GridFS does not support multi-document transactions.
Changed in version 3.7: Added the disable_md5 parameter.
Changed in version 3.1: Indexes are only ensured on the first write to the DB.
Changed in version 3.0: database must use an acknowledged
write_concern
See also
The MongoDB documentation on gridfs.
- delete(file_id: Any, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Delete a file from GridFS by
"_id"
.Deletes 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.
Note
Deletes of non-existent files are considered successful since the end result is the same: no file with that _id remains.
- Parameters
file_id:
"_id"
of the file to deletesession (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.Changed in version 3.1:
delete
no longer ensures indexes.
- exists(document_or_id: Optional[Any] = None, session: Optional[pymongo.client_session.ClientSession] = None, **kwargs: Any) bool ¶
Check if a file exists in this instance of
GridFS
.The file to check for can be specified by the value of its
_id
key, or by passing in a query document. A query document can be passed in as dictionary, or by using keyword arguments. Thus, the following three calls are equivalent:>>> fs.exists(file_id) >>> fs.exists({"_id": file_id}) >>> fs.exists(_id=file_id)
As are the following two calls:
>>> fs.exists({"filename": "mike.txt"}) >>> fs.exists(filename="mike.txt")
And the following two:
>>> fs.exists({"foo": {"$gt": 12}}) >>> fs.exists(foo={"$gt": 12})
Returns
True
if a matching file exists,False
otherwise. Calls toexists()
will not automatically create appropriate indexes; application developers should be sure to create indexes if needed and as appropriate.- Parameters
document_or_id (optional): query document, or _id of the document to check for
session (optional): a
ClientSession
**kwargs (optional): keyword arguments are used as a query document, if they’re present.
Changed in version 3.6: Added
session
parameter.
- find(*args: Any, **kwargs: Any) gridfs.grid_file.GridOutCursor ¶
Query GridFS for files.
Returns a cursor that iterates across files matching arbitrary queries on the files collection. Can be combined with other modifiers for additional control. For example:
for grid_out in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_out.read()
would iterate through all versions of “lisa.txt” stored in GridFS. Note that setting no_cursor_timeout to True may be important to prevent the cursor from timing out during long multi-file processing work.
As another example, the call:
most_recent_three = fs.find().sort("uploadDate", -1).limit(3)
would return a cursor to the three most recently uploaded files in GridFS.
Follows a similar interface to
find()
inCollection
.If a
ClientSession
is passed tofind()
, all returnedGridOut
instances are associated with that session.- Parameters
filter (optional): A query document that selects which files to include in the result set. Can be an empty document to include all files.
skip (optional): the number of files to omit (from the start of the result set) when returning the results
limit (optional): the maximum number of results to return
no_cursor_timeout (optional): if False (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to True, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with no_cursor_timeout turned on are properly closed.
sort (optional): a list of (key, direction) pairs specifying the sort order for this query. See
sort()
for details.
Raises
TypeError
if any of the arguments are of improper type. Returns an instance ofGridOutCursor
corresponding to this query.Changed in version 3.0: Removed the read_preference, tag_sets, and secondary_acceptable_latency_ms options.
New in version 2.7.
See also
The MongoDB documentation on find.
- find_one(filter: Optional[Any] = None, session: Optional[pymongo.client_session.ClientSession] = None, *args: Any, **kwargs: Any) Optional[gridfs.grid_file.GridOut] ¶
Get a single file from gridfs.
All arguments to
find()
are also valid arguments forfind_one()
, although any limit argument will be ignored. Returns a singleGridOut
, orNone
if no matching file is found. For example:file = fs.find_one({"filename": "lisa.txt"})
- Parameters
filter (optional): a dictionary specifying the query to be performing OR any other type to be used as the value for a query for
"_id"
in the file collection.*args (optional): any additional positional arguments are the same as the arguments to
find()
.session (optional): a
ClientSession
**kwargs (optional): any additional keyword arguments are the same as the arguments to
find()
.
Changed in version 3.6: Added
session
parameter.
- get(file_id: Any, session: Optional[pymongo.client_session.ClientSession] = None) gridfs.grid_file.GridOut ¶
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 getsession (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- get_last_version(filename: Optional[str] = None, session: Optional[pymongo.client_session.ClientSession] = None, **kwargs: Any) gridfs.grid_file.GridOut ¶
Get the most recent version of a file in GridFS by
"filename"
or metadata fields.Equivalent to calling
get_version()
with the default version (-1
).- Parameters
filename:
"filename"
of the file to get, or Nonesession (optional): a
ClientSession
**kwargs (optional): find files by custom metadata.
Changed in version 3.6: Added
session
parameter.
- get_version(filename: Optional[str] = None, version: Optional[int] = - 1, session: Optional[pymongo.client_session.ClientSession] = None, **kwargs: Any) gridfs.grid_file.GridOut ¶
Get a file from GridFS by
"filename"
or metadata fields.Returns a version of the file in GridFS whose filename matches filename and whose metadata fields match the supplied keyword arguments, as an instance of
GridOut
.Version numbering is a convenience atop the GridFS API provided by MongoDB. If more than one file matches the query (either by filename alone, by metadata fields, or by a combination of both), then version
-1
will be the most recently uploaded matching file,-2
the second most recently uploaded, etc. Version0
will be the first version uploaded,1
the second version, etc. So if three versions have been uploaded, then version0
is the same as version-3
, version1
is the same as version-2
, and version2
is the same as version-1
.Raises
NoFile
if no such version of that file exists.- Parameters
filename:
"filename"
of the file to get, or Noneversion (optional): version of the file to get (defaults to -1, the most recent version uploaded)
session (optional): a
ClientSession
**kwargs (optional): find files by custom metadata.
Changed in version 3.6: Added
session
parameter.Changed in version 3.1:
get_version
no longer ensures indexes.
- list(session: Optional[pymongo.client_session.ClientSession] = None) List[str] ¶
List the names of all files stored in this instance of
GridFS
.- Parameters
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.Changed in version 3.1:
list
no longer ensures indexes.
- new_file(**kwargs: Any) gridfs.grid_file.GridIn ¶
Create a new file in GridFS.
Returns a new
GridIn
instance to which data can be written. Any keyword arguments will be passed through toGridIn()
.If the
"_id"
of the file is manually specified, it must not already exist in GridFS. OtherwiseFileExists
is raised.- Parameters
**kwargs (optional): keyword arguments for file creation
- put(data: Any, **kwargs: Any) Any ¶
Put data in GridFS as a new file.
Equivalent to doing:
with fs.new_file(**kwargs) as f: f.write(data)
data can be either an instance of
bytes
or a file-like object providing aread()
method. If an encoding keyword argument is passed, data can also be astr
instance, which will be encoded as encoding before being written. Any keyword arguments will be passed through to the created file - seeGridIn()
for possible arguments. Returns the"_id"
of the created file.If the
"_id"
of the file is manually specified, it must not already exist in GridFS. OtherwiseFileExists
is raised.- Parameters
data: data to be written as a file.
**kwargs (optional): keyword arguments for file creation
Changed in version 3.0: w=0 writes to GridFS are now prohibited.
- class gridfs.GridFSBucket(db: pymongo.database.Database, bucket_name: str = 'fs', chunk_size_bytes: int = 261120, write_concern: Optional[pymongo.write_concern.WriteConcern] = None, read_preference: Optional[pymongo.read_preferences._ServerMode] = None)¶
Create a new instance of
GridFSBucket
.Raises
TypeError
if database is not an instance ofDatabase
.Raises
ConfigurationError
if write_concern is not acknowledged.- Parameters
database: database to use.
bucket_name (optional): The name of the bucket. Defaults to ‘fs’.
chunk_size_bytes (optional): The chunk size in bytes. Defaults to 255KB.
write_concern (optional): The
WriteConcern
to use. IfNone
(the default) db.write_concern is used.read_preference (optional): The read preference to use. If
None
(the default) db.read_preference is used.
Changed in version 4.0: Removed the disable_md5 parameter. See disable_md5 parameter is removed for details.
Changed in version 3.11: Running a GridFSBucket operation in a transaction now always raises an error. GridFSBucket does not support multi-document transactions.
Changed in version 3.7: Added the disable_md5 parameter.
New in version 3.1.
See also
The MongoDB documentation on gridfs.
- delete(file_id: Any, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Given an file_id, delete this stored file’s files collection document and associated chunks from a GridFS bucket.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to delete file_id = fs.upload_from_stream("test_file", "data I want to store!") fs.delete(file_id)
Raises
NoFile
if no file with file_id exists.- Parameters
file_id: The _id of the file to be deleted.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- download_to_stream(file_id: Any, destination: Any, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Downloads the contents of the stored file specified by file_id and writes the contents to destination.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to read file_id = fs.upload_from_stream("test_file", "data I want to store!") # Get file to write to file = open('myfile','wb+') fs.download_to_stream(file_id, file) file.seek(0) contents = file.read()
Raises
NoFile
if no file with file_id exists.- Parameters
file_id: The _id of the file to be downloaded.
destination: a file-like object implementing
write()
.session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- download_to_stream_by_name(filename: str, destination: Any, revision: int = - 1, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Write the contents of filename (with optional revision) to destination.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) # Get file to write to file = open('myfile','wb') fs.download_to_stream_by_name("test_file", file)
Raises
NoFile
if no such version of that file exists.Raises
ValueError
if filename is not a string.- Parameters
filename: The name of the file to read from.
destination: A file-like object that implements
write()
.revision (optional): Which revision (documents with the same filename and different uploadDate) of the file to retrieve. Defaults to -1 (the most recent revision).
session (optional): a
ClientSession
- Note
Revision numbers are defined as follows:
0 = the original stored file
1 = the first revision
2 = the second revision
etc…
-2 = the second most recent revision
-1 = the most recent revision
Changed in version 3.6: Added
session
parameter.
- find(*args: Any, **kwargs: Any) gridfs.grid_file.GridOutCursor ¶
Find and return the files collection documents that match
filter
Returns a cursor that iterates across files matching arbitrary queries on the files collection. Can be combined with other modifiers for additional control.
For example:
for grid_data in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_data.read()
would iterate through all versions of “lisa.txt” stored in GridFS. Note that setting no_cursor_timeout to True may be important to prevent the cursor from timing out during long multi-file processing work.
As another example, the call:
most_recent_three = fs.find().sort("uploadDate", -1).limit(3)
would return a cursor to the three most recently uploaded files in GridFS.
Follows a similar interface to
find()
inCollection
.If a
ClientSession
is passed tofind()
, all returnedGridOut
instances are associated with that session.- Parameters
filter: Search query.
batch_size (optional): The number of documents to return per batch.
limit (optional): The maximum number of documents to return.
no_cursor_timeout (optional): The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to True prevent that.
skip (optional): The number of documents to skip before returning.
sort (optional): The order by which to sort results. Defaults to None.
- open_download_stream(file_id: Any, session: Optional[pymongo.client_session.ClientSession] = None) gridfs.grid_file.GridOut ¶
Opens a Stream from which the application can read the contents of the stored file specified by file_id.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) # get _id of file to read. file_id = fs.upload_from_stream("test_file", "data I want to store!") grid_out = fs.open_download_stream(file_id) contents = grid_out.read()
Returns an instance of
GridOut
.Raises
NoFile
if no file with file_id exists.- Parameters
file_id: The _id of the file to be downloaded.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- open_download_stream_by_name(filename: str, revision: int = - 1, session: Optional[pymongo.client_session.ClientSession] = None) gridfs.grid_file.GridOut ¶
Opens a Stream from which the application can read the contents of filename and optional revision.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) grid_out = fs.open_download_stream_by_name("test_file") contents = grid_out.read()
Returns an instance of
GridOut
.Raises
NoFile
if no such version of that file exists.Raises
ValueError
filename is not a string.- Parameters
filename: The name of the file to read from.
revision (optional): Which revision (documents with the same filename and different uploadDate) of the file to retrieve. Defaults to -1 (the most recent revision).
session (optional): a
ClientSession
- Note
Revision numbers are defined as follows:
0 = the original stored file
1 = the first revision
2 = the second revision
etc…
-2 = the second most recent revision
-1 = the most recent revision
Changed in version 3.6: Added
session
parameter.
- open_upload_stream(filename: str, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[pymongo.client_session.ClientSession] = None) gridfs.grid_file.GridIn ¶
Opens a Stream that the application can write the contents of the file to.
The user must specify the filename, and can choose to add any additional information in the metadata field of the file document or modify the chunk size. For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream( "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"}) as grid_in: grid_in.write("data I want to store!") # uploaded on close
Returns an instance of
GridIn
.Raises
NoFile
if no such version of that file exists. RaisesValueError
if filename is not a string.- Parameters
filename: The name of the file to upload.
chunk_size_bytes (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes in
GridFSBucket
.metadata (optional): User data for the ‘metadata’ field of the files collection document. If not provided the metadata field will be omitted from the files collection document.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- open_upload_stream_with_id(file_id: Any, filename: str, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[pymongo.client_session.ClientSession] = None) gridfs.grid_file.GridIn ¶
Opens a Stream that the application can write the contents of the file to.
The user must specify the file id and filename, and can choose to add any additional information in the metadata field of the file document or modify the chunk size. For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) with fs.open_upload_stream_with_id( ObjectId(), "test_file", chunk_size_bytes=4, metadata={"contentType": "text/plain"}) as grid_in: grid_in.write("data I want to store!") # uploaded on close
Returns an instance of
GridIn
.Raises
NoFile
if no such version of that file exists. RaisesValueError
if filename is not a string.- Parameters
file_id: The id to use for this file. The id must not have already been used for another file.
filename: The name of the file to upload.
chunk_size_bytes (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes in
GridFSBucket
.metadata (optional): User data for the ‘metadata’ field of the files collection document. If not provided the metadata field will be omitted from the files collection document.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- rename(file_id: Any, new_filename: str, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Renames the stored file with the specified file_id.
For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to rename file_id = fs.upload_from_stream("test_file", "data I want to store!") fs.rename(file_id, "new_test_name")
Raises
NoFile
if no file with file_id exists.- Parameters
file_id: The _id of the file to be renamed.
new_filename: The new name of the file.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- upload_from_stream(filename: str, source: Any, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[pymongo.client_session.ClientSession] = None) bson.objectid.ObjectId ¶
Uploads a user file to a GridFS bucket.
Reads the contents of the user file from source and uploads it to the file filename. Source can be a string or file-like object. For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) file_id = fs.upload_from_stream( "test_file", "data I want to store!", chunk_size_bytes=4, metadata={"contentType": "text/plain"})
Returns the _id of the uploaded file.
Raises
NoFile
if no such version of that file exists. RaisesValueError
if filename is not a string.- Parameters
filename: The name of the file to upload.
source: The source stream of the content to be uploaded. Must be a file-like object that implements
read()
or a string.chunk_size_bytes (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes of
GridFSBucket
.metadata (optional): User data for the ‘metadata’ field of the files collection document. If not provided the metadata field will be omitted from the files collection document.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- upload_from_stream_with_id(file_id: Any, filename: str, source: Any, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[pymongo.client_session.ClientSession] = None) None ¶
Uploads a user file to a GridFS bucket with a custom file id.
Reads the contents of the user file from source and uploads it to the file filename. Source can be a string or file-like object. For example:
my_db = MongoClient().test fs = GridFSBucket(my_db) file_id = fs.upload_from_stream( ObjectId(), "test_file", "data I want to store!", chunk_size_bytes=4, metadata={"contentType": "text/plain"})
Raises
NoFile
if no such version of that file exists. RaisesValueError
if filename is not a string.- Parameters
file_id: The id to use for this file. The id must not have already been used for another file.
filename: The name of the file to upload.
source: The source stream of the content to be uploaded. Must be a file-like object that implements
read()
or a string.chunk_size_bytes (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes of
GridFSBucket
.metadata (optional): User data for the ‘metadata’ field of the files collection document. If not provided the metadata field will be omitted from the files collection document.
session (optional): a
ClientSession
Changed in version 3.6: Added
session
parameter.
- class gridfs.GridIn(root_collection: pymongo.collection.Collection, session: Optional[pymongo.client_session.ClientSession] = None, **kwargs: Any)¶
Write a file to GridFS
Application developers should generally not need to instantiate this class directly - instead see the methods provided by
GridFS
.Raises
TypeError
if root_collection is not an instance ofCollection
.Any of the file level options specified in the GridFS Spec may be passed as keyword arguments. Any additional keyword arguments will be set as additional fields on the file document. Valid keyword arguments include:
"_id"
: unique ID for this file (default:ObjectId
) - this"_id"
must not have already been used for another file"filename"
: human name for the file"contentType"
or"content_type"
: valid mime-type for the file"chunkSize"
or"chunk_size"
: size of each of the chunks, in bytes (default: 255 kb)"encoding"
: encoding used for this file. Anystr
that is written to the file will be converted tobytes
.
- Parameters
root_collection: root collection to write to
session (optional): a
ClientSession
to use for all commands**kwargs: Any (optional): file level options (see above)
Changed in version 4.0: Removed the disable_md5 parameter. See disable_md5 parameter is removed for details.
Changed in version 3.7: Added the disable_md5 parameter.
Changed in version 3.6: Added
session
parameter.Changed in version 3.0: root_collection must use an acknowledged
write_concern
- property chunk_size: Any¶
Chunk size for this file.
This attribute is read-only.
- close() None ¶
Flush the file and close it.
A closed file cannot be written any more. Calling
close()
more than once is allowed.
- property content_type: Any¶
Mime-type for this file.
- property filename: Any¶
Name of this file.
- property length: Any¶
Length (in bytes) of this file.
This attribute is read-only and can only be read after
close()
has been called.
- property md5: Any¶
MD5 of the contents of this file if an md5 sum was created.
This attribute is read-only and can only be read after
close()
has been called.
- property name: Any¶
Alias for filename.
- property upload_date: Any¶
Date that this file was uploaded.
This attribute is read-only and can only be read after
close()
has been called.
- write(data: Any) None ¶
Write data to the file. There is no return value.
data can be either a string of bytes or a file-like object (implementing
read()
). If the file has anencoding
attribute, data can also be astr
instance, which will be encoded asencoding
before being written.Due to buffering, the data may not actually be written to the database until the
close()
method is called. RaisesValueError
if this file is already closed. RaisesTypeError
if data is not an instance ofbytes
, a file-like object, or an instance ofstr
. Unicode data is only allowed if the file has anencoding
attribute.- Parameters
data: string of bytes or file-like object to be written to the file
- class gridfs.GridOut(root_collection: pymongo.collection.Collection, file_id: Optional[int] = None, file_document: Optional[Any] = None, session: Optional[pymongo.client_session.ClientSession] = None)¶
Read a file from GridFS
Application developers should generally not need to instantiate this class directly - instead see the methods provided by
GridFS
.Either file_id or file_document must be specified, file_document will be given priority if present. Raises
TypeError
if root_collection is not an instance ofCollection
.- Parameters
root_collection: root collection to read from
file_id (optional): value of
"_id"
for the file to readfile_document (optional): file document from root_collection.files
session (optional): a
ClientSession
to use for all commands
Changed in version 3.8: For better performance and to better follow the GridFS spec,
GridOut
now uses a single cursor to read all the chunks in the file.Changed in version 3.6: Added
session
parameter.Changed in version 3.0: Creating a GridOut does not immediately retrieve the file metadata from the server. Metadata is fetched when first needed.
- property aliases: Any¶
List of aliases for this file.
This attribute is read-only.
- property chunk_size: Any¶
Chunk size for this file.
This attribute is read-only.
- property content_type: Any¶
Mime-type for this file.
This attribute is read-only.
- property filename: Any¶
Name of this file.
This attribute is read-only.
- fileno() NoReturn ¶
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush() None ¶
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty() bool ¶
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- property length: Any¶
Length (in bytes) of this file.
This attribute is read-only.
- property md5: Any¶
MD5 of the contents of this file if an md5 sum was created.
This attribute is read-only.
- property metadata: Any¶
Metadata attached to this file.
This attribute is read-only.
- property name: Any¶
Alias for filename.
This attribute is read-only.
- read(size: int = - 1) bytes ¶
Read at most size bytes from the file (less if there isn’t enough data).
The bytes are returned as an instance of
str
(bytes
in python 3). If size is negative or omitted all data is read.- Parameters
size (optional): the number of bytes to read
Changed in version 3.8: This method now only checks for extra chunks after reading the entire file. Previously, this method would check for extra chunks on every call.
- readable() bool ¶
Return whether object was opened for reading.
If False, read() will raise OSError.
- readchunk() bytes ¶
Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned.
- readline(size: int = - 1) bytes ¶
Read one line or up to size bytes from the file.
- Parameters
size (optional): the maximum number of bytes to read
- seek(pos: int, whence: int = 0) int ¶
Set the current position of this file.
- Parameters
pos: the position (or offset if using relative positioning) to seek to
whence (optional): where to seek from.
os.SEEK_SET
(0
) for absolute file positioning,os.SEEK_CUR
(1
) to seek relative to the current position,os.SEEK_END
(2
) to seek relative to the file’s end.
Changed in version 4.1: The method now returns the new position in the file, to conform to the behavior of
io.IOBase.seek()
.
- seekable() bool ¶
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- truncate(size: Optional[int] = None) NoReturn ¶
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size.
- property upload_date: Any¶
Date that this file was first uploaded.
This attribute is read-only.
- class gridfs.GridOutCursor(collection: pymongo.collection.Collection, filter: Optional[Mapping[str, Any]] = None, skip: int = 0, limit: int = 0, no_cursor_timeout: bool = False, sort: Optional[Any] = None, batch_size: int = 0, session: Optional[pymongo.client_session.ClientSession] = None)¶
Create a new cursor, similar to the normal
Cursor
.Should not be called directly by application developers - see the
GridFS
methodfind()
instead.See also
The MongoDB documentation on cursors.
- add_option(*args: Any, **kwargs: Any) NoReturn ¶
Set arbitrary query flags using a bitmask.
To set the tailable flag: cursor.add_option(2)
- next() gridfs.grid_file.GridOut ¶
Get next GridOut object from cursor.
- exception gridfs.NoFile(message: str = '', error_labels: Optional[Iterable[str]] = None)¶
Raised when trying to read from a non-existent file.
Sub-modules: