grid_file.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. # Copyright 2009-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tools for representing files stored in GridFS."""
  15. import datetime
  16. import hashlib
  17. import io
  18. import math
  19. import os
  20. from bson.int64 import Int64
  21. from bson.son import SON
  22. from bson.binary import Binary
  23. from bson.objectid import ObjectId
  24. from bson.py3compat import text_type, StringIO
  25. from gridfs.errors import CorruptGridFile, FileExists, NoFile
  26. from pymongo import ASCENDING
  27. from pymongo.collection import Collection
  28. from pymongo.cursor import Cursor
  29. from pymongo.errors import (ConfigurationError,
  30. CursorNotFound,
  31. DuplicateKeyError,
  32. InvalidOperation,
  33. OperationFailure)
  34. from pymongo.read_preferences import ReadPreference
  35. try:
  36. _SEEK_SET = os.SEEK_SET
  37. _SEEK_CUR = os.SEEK_CUR
  38. _SEEK_END = os.SEEK_END
  39. # before 2.5
  40. except AttributeError:
  41. _SEEK_SET = 0
  42. _SEEK_CUR = 1
  43. _SEEK_END = 2
  44. EMPTY = b""
  45. NEWLN = b"\n"
  46. """Default chunk size, in bytes."""
  47. # Slightly under a power of 2, to work well with server's record allocations.
  48. DEFAULT_CHUNK_SIZE = 255 * 1024
  49. _C_INDEX = SON([("files_id", ASCENDING), ("n", ASCENDING)])
  50. _F_INDEX = SON([("filename", ASCENDING), ("uploadDate", ASCENDING)])
  51. def _grid_in_property(field_name, docstring, read_only=False,
  52. closed_only=False):
  53. """Create a GridIn property."""
  54. def getter(self):
  55. if closed_only and not self._closed:
  56. raise AttributeError("can only get %r on a closed file" %
  57. field_name)
  58. # Protect against PHP-237
  59. if field_name == 'length':
  60. return self._file.get(field_name, 0)
  61. return self._file.get(field_name, None)
  62. def setter(self, value):
  63. if self._closed:
  64. self._coll.files.update_one({"_id": self._file["_id"]},
  65. {"$set": {field_name: value}})
  66. self._file[field_name] = value
  67. if read_only:
  68. docstring += "\n\nThis attribute is read-only."
  69. elif closed_only:
  70. docstring = "%s\n\n%s" % (docstring, "This attribute is read-only and "
  71. "can only be read after :meth:`close` "
  72. "has been called.")
  73. if not read_only and not closed_only:
  74. return property(getter, setter, doc=docstring)
  75. return property(getter, doc=docstring)
  76. def _grid_out_property(field_name, docstring):
  77. """Create a GridOut property."""
  78. def getter(self):
  79. self._ensure_file()
  80. # Protect against PHP-237
  81. if field_name == 'length':
  82. return self._file.get(field_name, 0)
  83. return self._file.get(field_name, None)
  84. docstring += "\n\nThis attribute is read-only."
  85. return property(getter, doc=docstring)
  86. def _clear_entity_type_registry(entity, **kwargs):
  87. """Clear the given database/collection object's type registry."""
  88. codecopts = entity.codec_options.with_options(type_registry=None)
  89. return entity.with_options(codec_options=codecopts, **kwargs)
  90. def _disallow_transactions(session):
  91. if session and session.in_transaction:
  92. raise InvalidOperation(
  93. 'GridFS does not support multi-document transactions')
  94. class GridIn(object):
  95. """Class to write data to GridFS.
  96. """
  97. def __init__(
  98. self, root_collection, session=None, disable_md5=False, **kwargs):
  99. """Write a file to GridFS
  100. Application developers should generally not need to
  101. instantiate this class directly - instead see the methods
  102. provided by :class:`~gridfs.GridFS`.
  103. Raises :class:`TypeError` if `root_collection` is not an
  104. instance of :class:`~pymongo.collection.Collection`.
  105. Any of the file level options specified in the `GridFS Spec
  106. <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as
  107. keyword arguments. Any additional keyword arguments will be
  108. set as additional fields on the file document. Valid keyword
  109. arguments include:
  110. - ``"_id"``: unique ID for this file (default:
  111. :class:`~bson.objectid.ObjectId`) - this ``"_id"`` must
  112. not have already been used for another file
  113. - ``"filename"``: human name for the file
  114. - ``"contentType"`` or ``"content_type"``: valid mime-type
  115. for the file
  116. - ``"chunkSize"`` or ``"chunk_size"``: size of each of the
  117. chunks, in bytes (default: 255 kb)
  118. - ``"encoding"``: encoding used for this file. In Python 2,
  119. any :class:`unicode` that is written to the file will be
  120. converted to a :class:`str`. In Python 3, any :class:`str`
  121. that is written to the file will be converted to
  122. :class:`bytes`.
  123. :Parameters:
  124. - `root_collection`: root collection to write to
  125. - `session` (optional): a
  126. :class:`~pymongo.client_session.ClientSession` to use for all
  127. commands
  128. - `disable_md5` (optional): When True, an MD5 checksum will not be
  129. computed for the uploaded file. Useful in environments where
  130. MD5 cannot be used for regulatory or other reasons. Defaults to
  131. False.
  132. - `**kwargs` (optional): file level options (see above)
  133. .. versionchanged:: 3.6
  134. Added ``session`` parameter.
  135. .. versionchanged:: 3.0
  136. `root_collection` must use an acknowledged
  137. :attr:`~pymongo.collection.Collection.write_concern`
  138. """
  139. if not isinstance(root_collection, Collection):
  140. raise TypeError("root_collection must be an "
  141. "instance of Collection")
  142. if not root_collection.write_concern.acknowledged:
  143. raise ConfigurationError('root_collection must use '
  144. 'acknowledged write_concern')
  145. _disallow_transactions(session)
  146. # Handle alternative naming
  147. if "content_type" in kwargs:
  148. kwargs["contentType"] = kwargs.pop("content_type")
  149. if "chunk_size" in kwargs:
  150. kwargs["chunkSize"] = kwargs.pop("chunk_size")
  151. coll = _clear_entity_type_registry(
  152. root_collection, read_preference=ReadPreference.PRIMARY)
  153. if not disable_md5:
  154. kwargs["md5"] = hashlib.md5()
  155. # Defaults
  156. kwargs["_id"] = kwargs.get("_id", ObjectId())
  157. kwargs["chunkSize"] = kwargs.get("chunkSize", DEFAULT_CHUNK_SIZE)
  158. object.__setattr__(self, "_session", session)
  159. object.__setattr__(self, "_coll", coll)
  160. object.__setattr__(self, "_chunks", coll.chunks)
  161. object.__setattr__(self, "_file", kwargs)
  162. object.__setattr__(self, "_buffer", StringIO())
  163. object.__setattr__(self, "_position", 0)
  164. object.__setattr__(self, "_chunk_number", 0)
  165. object.__setattr__(self, "_closed", False)
  166. object.__setattr__(self, "_ensured_index", False)
  167. def __create_index(self, collection, index_key, unique):
  168. doc = collection.find_one(projection={"_id": 1}, session=self._session)
  169. if doc is None:
  170. try:
  171. index_keys = [index_spec['key'] for index_spec in
  172. collection.list_indexes(session=self._session)]
  173. except OperationFailure:
  174. index_keys = []
  175. if index_key not in index_keys:
  176. collection.create_index(
  177. index_key.items(), unique=unique, session=self._session)
  178. def __ensure_indexes(self):
  179. if not object.__getattribute__(self, "_ensured_index"):
  180. _disallow_transactions(self._session)
  181. self.__create_index(self._coll.files, _F_INDEX, False)
  182. self.__create_index(self._coll.chunks, _C_INDEX, True)
  183. object.__setattr__(self, "_ensured_index", True)
  184. def abort(self):
  185. """Remove all chunks/files that may have been uploaded and close.
  186. """
  187. self._coll.chunks.delete_many(
  188. {"files_id": self._file['_id']}, session=self._session)
  189. self._coll.files.delete_one(
  190. {"_id": self._file['_id']}, session=self._session)
  191. object.__setattr__(self, "_closed", True)
  192. @property
  193. def closed(self):
  194. """Is this file closed?
  195. """
  196. return self._closed
  197. _id = _grid_in_property("_id", "The ``'_id'`` value for this file.",
  198. read_only=True)
  199. filename = _grid_in_property("filename", "Name of this file.")
  200. name = _grid_in_property("filename", "Alias for `filename`.")
  201. content_type = _grid_in_property("contentType", "Mime-type for this file.")
  202. length = _grid_in_property("length", "Length (in bytes) of this file.",
  203. closed_only=True)
  204. chunk_size = _grid_in_property("chunkSize", "Chunk size for this file.",
  205. read_only=True)
  206. upload_date = _grid_in_property("uploadDate",
  207. "Date that this file was uploaded.",
  208. closed_only=True)
  209. md5 = _grid_in_property("md5", "MD5 of the contents of this file "
  210. "if an md5 sum was created.",
  211. closed_only=True)
  212. def __getattr__(self, name):
  213. if name in self._file:
  214. return self._file[name]
  215. raise AttributeError("GridIn object has no attribute '%s'" % name)
  216. def __setattr__(self, name, value):
  217. # For properties of this instance like _buffer, or descriptors set on
  218. # the class like filename, use regular __setattr__
  219. if name in self.__dict__ or name in self.__class__.__dict__:
  220. object.__setattr__(self, name, value)
  221. else:
  222. # All other attributes are part of the document in db.fs.files.
  223. # Store them to be sent to server on close() or if closed, send
  224. # them now.
  225. self._file[name] = value
  226. if self._closed:
  227. self._coll.files.update_one({"_id": self._file["_id"]},
  228. {"$set": {name: value}})
  229. def __flush_data(self, data):
  230. """Flush `data` to a chunk.
  231. """
  232. self.__ensure_indexes()
  233. if 'md5' in self._file:
  234. self._file['md5'].update(data)
  235. if not data:
  236. return
  237. assert(len(data) <= self.chunk_size)
  238. chunk = {"files_id": self._file["_id"],
  239. "n": self._chunk_number,
  240. "data": Binary(data)}
  241. try:
  242. self._chunks.insert_one(chunk, session=self._session)
  243. except DuplicateKeyError:
  244. self._raise_file_exists(self._file['_id'])
  245. self._chunk_number += 1
  246. self._position += len(data)
  247. def __flush_buffer(self):
  248. """Flush the buffer contents out to a chunk.
  249. """
  250. self.__flush_data(self._buffer.getvalue())
  251. self._buffer.close()
  252. self._buffer = StringIO()
  253. def __flush(self):
  254. """Flush the file to the database.
  255. """
  256. try:
  257. self.__flush_buffer()
  258. if "md5" in self._file:
  259. self._file["md5"] = self._file["md5"].hexdigest()
  260. # The GridFS spec says length SHOULD be an Int64.
  261. self._file["length"] = Int64(self._position)
  262. self._file["uploadDate"] = datetime.datetime.utcnow()
  263. return self._coll.files.insert_one(
  264. self._file, session=self._session)
  265. except DuplicateKeyError:
  266. self._raise_file_exists(self._id)
  267. def _raise_file_exists(self, file_id):
  268. """Raise a FileExists exception for the given file_id."""
  269. raise FileExists("file with _id %r already exists" % file_id)
  270. def close(self):
  271. """Flush the file and close it.
  272. A closed file cannot be written any more. Calling
  273. :meth:`close` more than once is allowed.
  274. """
  275. if not self._closed:
  276. self.__flush()
  277. object.__setattr__(self, "_closed", True)
  278. def read(self, size=-1):
  279. raise io.UnsupportedOperation('read')
  280. def readable(self):
  281. return False
  282. def seekable(self):
  283. return False
  284. def write(self, data):
  285. """Write data to the file. There is no return value.
  286. `data` can be either a string of bytes or a file-like object
  287. (implementing :meth:`read`). If the file has an
  288. :attr:`encoding` attribute, `data` can also be a
  289. :class:`unicode` (:class:`str` in python 3) instance, which
  290. will be encoded as :attr:`encoding` before being written.
  291. Due to buffering, the data may not actually be written to the
  292. database until the :meth:`close` method is called. Raises
  293. :class:`ValueError` if this file is already closed. Raises
  294. :class:`TypeError` if `data` is not an instance of
  295. :class:`str` (:class:`bytes` in python 3), a file-like object,
  296. or an instance of :class:`unicode` (:class:`str` in python 3).
  297. Unicode data is only allowed if the file has an :attr:`encoding`
  298. attribute.
  299. :Parameters:
  300. - `data`: string of bytes or file-like object to be written
  301. to the file
  302. """
  303. if self._closed:
  304. raise ValueError("cannot write to a closed file")
  305. try:
  306. # file-like
  307. read = data.read
  308. except AttributeError:
  309. # string
  310. if not isinstance(data, (text_type, bytes)):
  311. raise TypeError("can only write strings or file-like objects")
  312. if isinstance(data, text_type):
  313. try:
  314. data = data.encode(self.encoding)
  315. except AttributeError:
  316. raise TypeError("must specify an encoding for file in "
  317. "order to write %s" % (text_type.__name__,))
  318. read = StringIO(data).read
  319. if self._buffer.tell() > 0:
  320. # Make sure to flush only when _buffer is complete
  321. space = self.chunk_size - self._buffer.tell()
  322. if space:
  323. try:
  324. to_write = read(space)
  325. except:
  326. self.abort()
  327. raise
  328. self._buffer.write(to_write)
  329. if len(to_write) < space:
  330. return # EOF or incomplete
  331. self.__flush_buffer()
  332. to_write = read(self.chunk_size)
  333. while to_write and len(to_write) == self.chunk_size:
  334. self.__flush_data(to_write)
  335. to_write = read(self.chunk_size)
  336. self._buffer.write(to_write)
  337. def writelines(self, sequence):
  338. """Write a sequence of strings to the file.
  339. Does not add seperators.
  340. """
  341. for line in sequence:
  342. self.write(line)
  343. def writeable(self):
  344. return True
  345. def __enter__(self):
  346. """Support for the context manager protocol.
  347. """
  348. return self
  349. def __exit__(self, exc_type, exc_val, exc_tb):
  350. """Support for the context manager protocol.
  351. Close the file and allow exceptions to propagate.
  352. """
  353. self.close()
  354. # propagate exceptions
  355. return False
  356. class GridOut(object):
  357. """Class to read data out of GridFS.
  358. """
  359. def __init__(self, root_collection, file_id=None, file_document=None,
  360. session=None):
  361. """Read a file from GridFS
  362. Application developers should generally not need to
  363. instantiate this class directly - instead see the methods
  364. provided by :class:`~gridfs.GridFS`.
  365. Either `file_id` or `file_document` must be specified,
  366. `file_document` will be given priority if present. Raises
  367. :class:`TypeError` if `root_collection` is not an instance of
  368. :class:`~pymongo.collection.Collection`.
  369. :Parameters:
  370. - `root_collection`: root collection to read from
  371. - `file_id` (optional): value of ``"_id"`` for the file to read
  372. - `file_document` (optional): file document from
  373. `root_collection.files`
  374. - `session` (optional): a
  375. :class:`~pymongo.client_session.ClientSession` to use for all
  376. commands
  377. .. versionchanged:: 3.8
  378. For better performance and to better follow the GridFS spec,
  379. :class:`GridOut` now uses a single cursor to read all the chunks in
  380. the file.
  381. .. versionchanged:: 3.6
  382. Added ``session`` parameter.
  383. .. versionchanged:: 3.0
  384. Creating a GridOut does not immediately retrieve the file metadata
  385. from the server. Metadata is fetched when first needed.
  386. """
  387. if not isinstance(root_collection, Collection):
  388. raise TypeError("root_collection must be an "
  389. "instance of Collection")
  390. _disallow_transactions(session)
  391. root_collection = _clear_entity_type_registry(root_collection)
  392. self.__chunks = root_collection.chunks
  393. self.__files = root_collection.files
  394. self.__file_id = file_id
  395. self.__buffer = EMPTY
  396. self.__chunk_iter = None
  397. self.__position = 0
  398. self._file = file_document
  399. self._session = session
  400. _id = _grid_out_property("_id", "The ``'_id'`` value for this file.")
  401. filename = _grid_out_property("filename", "Name of this file.")
  402. name = _grid_out_property("filename", "Alias for `filename`.")
  403. content_type = _grid_out_property("contentType", "Mime-type for this file.")
  404. length = _grid_out_property("length", "Length (in bytes) of this file.")
  405. chunk_size = _grid_out_property("chunkSize", "Chunk size for this file.")
  406. upload_date = _grid_out_property("uploadDate",
  407. "Date that this file was first uploaded.")
  408. aliases = _grid_out_property("aliases", "List of aliases for this file.")
  409. metadata = _grid_out_property("metadata", "Metadata attached to this file.")
  410. md5 = _grid_out_property("md5", "MD5 of the contents of this file "
  411. "if an md5 sum was created.")
  412. def _ensure_file(self):
  413. if not self._file:
  414. _disallow_transactions(self._session)
  415. self._file = self.__files.find_one({"_id": self.__file_id},
  416. session=self._session)
  417. if not self._file:
  418. raise NoFile("no file in gridfs collection %r with _id %r" %
  419. (self.__files, self.__file_id))
  420. def __getattr__(self, name):
  421. self._ensure_file()
  422. if name in self._file:
  423. return self._file[name]
  424. raise AttributeError("GridOut object has no attribute '%s'" % name)
  425. def readable(self):
  426. return True
  427. def readchunk(self):
  428. """Reads a chunk at a time. If the current position is within a
  429. chunk the remainder of the chunk is returned.
  430. """
  431. received = len(self.__buffer)
  432. chunk_data = EMPTY
  433. chunk_size = int(self.chunk_size)
  434. if received > 0:
  435. chunk_data = self.__buffer
  436. elif self.__position < int(self.length):
  437. chunk_number = int((received + self.__position) / chunk_size)
  438. if self.__chunk_iter is None:
  439. self.__chunk_iter = _GridOutChunkIterator(
  440. self, self.__chunks, self._session, chunk_number)
  441. chunk = self.__chunk_iter.next()
  442. chunk_data = chunk["data"][self.__position % chunk_size:]
  443. if not chunk_data:
  444. raise CorruptGridFile("truncated chunk")
  445. self.__position += len(chunk_data)
  446. self.__buffer = EMPTY
  447. return chunk_data
  448. def read(self, size=-1):
  449. """Read at most `size` bytes from the file (less if there
  450. isn't enough data).
  451. The bytes are returned as an instance of :class:`str` (:class:`bytes`
  452. in python 3). If `size` is negative or omitted all data is read.
  453. :Parameters:
  454. - `size` (optional): the number of bytes to read
  455. .. versionchanged:: 3.8
  456. This method now only checks for extra chunks after reading the
  457. entire file. Previously, this method would check for extra chunks
  458. on every call.
  459. """
  460. self._ensure_file()
  461. remainder = int(self.length) - self.__position
  462. if size < 0 or size > remainder:
  463. size = remainder
  464. if size == 0:
  465. return EMPTY
  466. received = 0
  467. data = StringIO()
  468. while received < size:
  469. chunk_data = self.readchunk()
  470. received += len(chunk_data)
  471. data.write(chunk_data)
  472. # Detect extra chunks after reading the entire file.
  473. if size == remainder and self.__chunk_iter:
  474. try:
  475. self.__chunk_iter.next()
  476. except StopIteration:
  477. pass
  478. self.__position -= received - size
  479. # Return 'size' bytes and store the rest.
  480. data.seek(size)
  481. self.__buffer = data.read()
  482. data.seek(0)
  483. return data.read(size)
  484. def readline(self, size=-1):
  485. """Read one line or up to `size` bytes from the file.
  486. :Parameters:
  487. - `size` (optional): the maximum number of bytes to read
  488. """
  489. remainder = int(self.length) - self.__position
  490. if size < 0 or size > remainder:
  491. size = remainder
  492. if size == 0:
  493. return EMPTY
  494. received = 0
  495. data = StringIO()
  496. while received < size:
  497. chunk_data = self.readchunk()
  498. pos = chunk_data.find(NEWLN, 0, size)
  499. if pos != -1:
  500. size = received + pos + 1
  501. received += len(chunk_data)
  502. data.write(chunk_data)
  503. if pos != -1:
  504. break
  505. self.__position -= received - size
  506. # Return 'size' bytes and store the rest.
  507. data.seek(size)
  508. self.__buffer = data.read()
  509. data.seek(0)
  510. return data.read(size)
  511. def tell(self):
  512. """Return the current position of this file.
  513. """
  514. return self.__position
  515. def seek(self, pos, whence=_SEEK_SET):
  516. """Set the current position of this file.
  517. :Parameters:
  518. - `pos`: the position (or offset if using relative
  519. positioning) to seek to
  520. - `whence` (optional): where to seek
  521. from. :attr:`os.SEEK_SET` (``0``) for absolute file
  522. positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative
  523. to the current position, :attr:`os.SEEK_END` (``2``) to
  524. seek relative to the file's end.
  525. """
  526. if whence == _SEEK_SET:
  527. new_pos = pos
  528. elif whence == _SEEK_CUR:
  529. new_pos = self.__position + pos
  530. elif whence == _SEEK_END:
  531. new_pos = int(self.length) + pos
  532. else:
  533. raise IOError(22, "Invalid value for `whence`")
  534. if new_pos < 0:
  535. raise IOError(22, "Invalid value for `pos` - must be positive")
  536. # Optimization, continue using the same buffer and chunk iterator.
  537. if new_pos == self.__position:
  538. return
  539. self.__position = new_pos
  540. self.__buffer = EMPTY
  541. if self.__chunk_iter:
  542. self.__chunk_iter.close()
  543. self.__chunk_iter = None
  544. def seekable(self):
  545. return True
  546. def __iter__(self):
  547. """Return an iterator over all of this file's data.
  548. The iterator will return chunk-sized instances of
  549. :class:`str` (:class:`bytes` in python 3). This can be
  550. useful when serving files using a webserver that handles
  551. such an iterator efficiently.
  552. .. note::
  553. This is different from :py:class:`io.IOBase` which iterates over
  554. *lines* in the file. Use :meth:`GridOut.readline` to read line by
  555. line instead of chunk by chunk.
  556. .. versionchanged:: 3.8
  557. The iterator now raises :class:`CorruptGridFile` when encountering
  558. any truncated, missing, or extra chunk in a file. The previous
  559. behavior was to only raise :class:`CorruptGridFile` on a missing
  560. chunk.
  561. """
  562. return GridOutIterator(self, self.__chunks, self._session)
  563. def close(self):
  564. """Make GridOut more generically file-like."""
  565. if self.__chunk_iter:
  566. self.__chunk_iter.close()
  567. self.__chunk_iter = None
  568. def write(self, value):
  569. raise io.UnsupportedOperation('write')
  570. def __enter__(self):
  571. """Makes it possible to use :class:`GridOut` files
  572. with the context manager protocol.
  573. """
  574. return self
  575. def __exit__(self, exc_type, exc_val, exc_tb):
  576. """Makes it possible to use :class:`GridOut` files
  577. with the context manager protocol.
  578. """
  579. self.close()
  580. return False
  581. class _GridOutChunkIterator(object):
  582. """Iterates over a file's chunks using a single cursor.
  583. Raises CorruptGridFile when encountering any truncated, missing, or extra
  584. chunk in a file.
  585. """
  586. def __init__(self, grid_out, chunks, session, next_chunk):
  587. self._id = grid_out._id
  588. self._chunk_size = int(grid_out.chunk_size)
  589. self._length = int(grid_out.length)
  590. self._chunks = chunks
  591. self._session = session
  592. self._next_chunk = next_chunk
  593. self._num_chunks = math.ceil(float(self._length) / self._chunk_size)
  594. self._cursor = None
  595. def expected_chunk_length(self, chunk_n):
  596. if chunk_n < self._num_chunks - 1:
  597. return self._chunk_size
  598. return self._length - (self._chunk_size * (self._num_chunks - 1))
  599. def __iter__(self):
  600. return self
  601. def _create_cursor(self):
  602. filter = {"files_id": self._id}
  603. if self._next_chunk > 0:
  604. filter["n"] = {"$gte": self._next_chunk}
  605. _disallow_transactions(self._session)
  606. self._cursor = self._chunks.find(filter, sort=[("n", 1)],
  607. session=self._session)
  608. def _next_with_retry(self):
  609. """Return the next chunk and retry once on CursorNotFound.
  610. We retry on CursorNotFound to maintain backwards compatibility in
  611. cases where two calls to read occur more than 10 minutes apart (the
  612. server's default cursor timeout).
  613. """
  614. if self._cursor is None:
  615. self._create_cursor()
  616. try:
  617. return self._cursor.next()
  618. except CursorNotFound:
  619. self._cursor.close()
  620. self._create_cursor()
  621. return self._cursor.next()
  622. def next(self):
  623. try:
  624. chunk = self._next_with_retry()
  625. except StopIteration:
  626. if self._next_chunk >= self._num_chunks:
  627. raise
  628. raise CorruptGridFile("no chunk #%d" % self._next_chunk)
  629. if chunk["n"] != self._next_chunk:
  630. self.close()
  631. raise CorruptGridFile(
  632. "Missing chunk: expected chunk #%d but found "
  633. "chunk with n=%d" % (self._next_chunk, chunk["n"]))
  634. if chunk["n"] >= self._num_chunks:
  635. # According to spec, ignore extra chunks if they are empty.
  636. if len(chunk["data"]):
  637. self.close()
  638. raise CorruptGridFile(
  639. "Extra chunk found: expected %d chunks but found "
  640. "chunk with n=%d" % (self._num_chunks, chunk["n"]))
  641. expected_length = self.expected_chunk_length(chunk["n"])
  642. if len(chunk["data"]) != expected_length:
  643. self.close()
  644. raise CorruptGridFile(
  645. "truncated chunk #%d: expected chunk length to be %d but "
  646. "found chunk with length %d" % (
  647. chunk["n"], expected_length, len(chunk["data"])))
  648. self._next_chunk += 1
  649. return chunk
  650. __next__ = next
  651. def close(self):
  652. if self._cursor:
  653. self._cursor.close()
  654. self._cursor = None
  655. class GridOutIterator(object):
  656. def __init__(self, grid_out, chunks, session):
  657. self.__chunk_iter = _GridOutChunkIterator(grid_out, chunks, session, 0)
  658. def __iter__(self):
  659. return self
  660. def next(self):
  661. chunk = self.__chunk_iter.next()
  662. return bytes(chunk["data"])
  663. __next__ = next
  664. class GridOutCursor(Cursor):
  665. """A cursor / iterator for returning GridOut objects as the result
  666. of an arbitrary query against the GridFS files collection.
  667. """
  668. def __init__(self, collection, filter=None, skip=0, limit=0,
  669. no_cursor_timeout=False, sort=None, batch_size=0,
  670. session=None):
  671. """Create a new cursor, similar to the normal
  672. :class:`~pymongo.cursor.Cursor`.
  673. Should not be called directly by application developers - see
  674. the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead.
  675. .. versionadded 2.7
  676. .. mongodoc:: cursors
  677. """
  678. _disallow_transactions(session)
  679. collection = _clear_entity_type_registry(collection)
  680. # Hold on to the base "fs" collection to create GridOut objects later.
  681. self.__root_collection = collection
  682. super(GridOutCursor, self).__init__(
  683. collection.files, filter, skip=skip, limit=limit,
  684. no_cursor_timeout=no_cursor_timeout, sort=sort,
  685. batch_size=batch_size, session=session)
  686. def next(self):
  687. """Get next GridOut object from cursor.
  688. """
  689. _disallow_transactions(self.session)
  690. # Work around "super is not iterable" issue in Python 3.x
  691. next_file = super(GridOutCursor, self).next()
  692. return GridOut(self.__root_collection, file_document=next_file,
  693. session=self.session)
  694. __next__ = next
  695. def add_option(self, *args, **kwargs):
  696. raise NotImplementedError("Method does not exist for GridOutCursor")
  697. def remove_option(self, *args, **kwargs):
  698. raise NotImplementedError("Method does not exist for GridOutCursor")
  699. def _clone_base(self, session):
  700. """Creates an empty GridOutCursor for information to be copied into.
  701. """
  702. return GridOutCursor(self.__root_collection, session=session)