Skip to content

Commit 1cfa801

Browse files
author
Mike Dirolf
committed
add file_document param to GridOut to initialize from existing file doc PYTHON-117
1 parent ee824ef commit 1cfa801

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

gridfs/grid_file.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -293,30 +293,38 @@ def __exit__(self, exc_type, exc_val, exc_tb):
293293
class GridOut(object):
294294
"""Class to read data out of GridFS.
295295
"""
296-
def __init__(self, root_collection, file_id):
296+
def __init__(self, root_collection, file_id=None, file_document=None):
297297
"""Read a file from GridFS
298298
299299
Application developers should generally not need to
300300
instantiate this class directly - instead see the methods
301301
provided by :class:`~gridfs.GridFS`.
302302
303-
Raises :class:`TypeError` if `root_collection` is not an instance of
303+
Either `file_id` or `file_document` must be specified,
304+
`file_document` will be given priority if present. Raises
305+
:class:`TypeError` if `root_collection` is not an instance of
304306
:class:`~pymongo.collection.Collection`.
305307
306308
:Parameters:
307309
- `root_collection`: root collection to read from
308310
- `file_id`: value of ``"_id"`` for the file to read
311+
- `file_document`: file document from `root_collection.files`
312+
313+
.. versionadded:: 1.8.1+
314+
The `file_document` parameter.
309315
"""
310316
if not isinstance(root_collection, Collection):
311317
raise TypeError("root_collection must be an "
312318
"instance of Collection")
313319

314320
self.__chunks = root_collection.chunks
315-
self._file = root_collection.files.find_one({"_id": file_id})
321+
322+
files = root_collection.files
323+
self._file = file_document or files.find_one({"_id": file_id})
316324

317325
if not self._file:
318326
raise NoFile("no file in gridfs collection %r with _id %r" %
319-
(root_collection, file_id))
327+
(files, file_id))
320328

321329
self.__buffer = ""
322330
self.__position = 0

test/test_grid_file.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,19 @@ def test_grid_out_custom_opts(self):
226226
"upload_date", "aliases", "metadata", "md5"]:
227227
self.assertRaises(AttributeError, setattr, b, attr, 5)
228228

229+
def test_grid_out_file_document(self):
230+
a = GridIn(self.db.fs)
231+
a.write("foo bar")
232+
a.close()
233+
234+
b = GridOut(self.db.fs, file_document=self.db.fs.files.find_one())
235+
self.assertEqual("foo bar", b.read())
236+
237+
c = GridOut(self.db.fs, 5, file_document=self.db.fs.files.find_one())
238+
self.assertEqual("foo bar", c.read())
239+
240+
self.assertRaises(NoFile, GridOut, self.db.fs, file_document={})
241+
229242
def test_write_file_like(self):
230243
a = GridIn(self.db.fs)
231244
a.write("hello world")

0 commit comments

Comments
 (0)