__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # Copyright 2009-2015 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. """GridFS is a specification for storing large objects in Mongo.
  15. The :mod:`gridfs` package is an implementation of GridFS on top of
  16. :mod:`pymongo`, exposing a file-like interface.
  17. .. mongodoc:: gridfs
  18. """
  19. from collections import Mapping
  20. from gridfs.errors import NoFile
  21. from gridfs.grid_file import (GridIn,
  22. GridOut,
  23. GridOutCursor)
  24. from pymongo import (ASCENDING,
  25. DESCENDING)
  26. from pymongo.database import Database
  27. from pymongo.errors import ConfigurationError
  28. class GridFS(object):
  29. """An instance of GridFS on top of a single Database.
  30. """
  31. def __init__(self, database, collection="fs"):
  32. """Create a new instance of :class:`GridFS`.
  33. Raises :class:`TypeError` if `database` is not an instance of
  34. :class:`~pymongo.database.Database`.
  35. :Parameters:
  36. - `database`: database to use
  37. - `collection` (optional): root collection to use
  38. .. versionchanged:: 3.0
  39. `database` must use an acknowledged
  40. :attr:`~pymongo.database.Database.write_concern`
  41. .. mongodoc:: gridfs
  42. """
  43. if not isinstance(database, Database):
  44. raise TypeError("database must be an instance of Database")
  45. if not database.write_concern.acknowledged:
  46. raise ConfigurationError('database must use '
  47. 'acknowledged write_concern')
  48. self.__database = database
  49. self.__collection = database[collection]
  50. self.__files = self.__collection.files
  51. self.__chunks = self.__collection.chunks
  52. def __is_secondary(self):
  53. return not self.__database.client._is_writable()
  54. def __ensure_index_files_id(self):
  55. if not self.__is_secondary():
  56. self.__chunks.create_index([("files_id", ASCENDING),
  57. ("n", ASCENDING)],
  58. unique=True)
  59. def __ensure_index_filename(self):
  60. if not self.__is_secondary():
  61. self.__files.create_index([("filename", ASCENDING),
  62. ("uploadDate", DESCENDING)])
  63. def new_file(self, **kwargs):
  64. """Create a new file in GridFS.
  65. Returns a new :class:`~gridfs.grid_file.GridIn` instance to
  66. which data can be written. Any keyword arguments will be
  67. passed through to :meth:`~gridfs.grid_file.GridIn`.
  68. If the ``"_id"`` of the file is manually specified, it must
  69. not already exist in GridFS. Otherwise
  70. :class:`~gridfs.errors.FileExists` is raised.
  71. :Parameters:
  72. - `**kwargs` (optional): keyword arguments for file creation
  73. """
  74. # No need for __ensure_index_files_id() here; GridIn ensures
  75. # the (files_id, n) index when needed.
  76. return GridIn(self.__collection, **kwargs)
  77. def put(self, data, **kwargs):
  78. """Put data in GridFS as a new file.
  79. Equivalent to doing::
  80. try:
  81. f = new_file(**kwargs)
  82. f.write(data)
  83. finally:
  84. f.close()
  85. `data` can be either an instance of :class:`str` (:class:`bytes`
  86. in python 3) or a file-like object providing a :meth:`read` method.
  87. If an `encoding` keyword argument is passed, `data` can also be a
  88. :class:`unicode` (:class:`str` in python 3) instance, which will
  89. be encoded as `encoding` before being written. Any keyword arguments
  90. will be passed through to the created file - see
  91. :meth:`~gridfs.grid_file.GridIn` for possible arguments. Returns the
  92. ``"_id"`` of the created file.
  93. If the ``"_id"`` of the file is manually specified, it must
  94. not already exist in GridFS. Otherwise
  95. :class:`~gridfs.errors.FileExists` is raised.
  96. :Parameters:
  97. - `data`: data to be written as a file.
  98. - `**kwargs` (optional): keyword arguments for file creation
  99. .. versionchanged:: 3.0
  100. w=0 writes to GridFS are now prohibited.
  101. """
  102. grid_file = GridIn(self.__collection, **kwargs)
  103. try:
  104. grid_file.write(data)
  105. finally:
  106. grid_file.close()
  107. return grid_file._id
  108. def get(self, file_id):
  109. """Get a file from GridFS by ``"_id"``.
  110. Returns an instance of :class:`~gridfs.grid_file.GridOut`,
  111. which provides a file-like interface for reading.
  112. :Parameters:
  113. - `file_id`: ``"_id"`` of the file to get
  114. """
  115. gout = GridOut(self.__collection, file_id)
  116. # Raise NoFile now, instead of on first attribute access.
  117. gout._ensure_file()
  118. return gout
  119. def get_version(self, filename=None, version=-1, **kwargs):
  120. """Get a file from GridFS by ``"filename"`` or metadata fields.
  121. Returns a version of the file in GridFS whose filename matches
  122. `filename` and whose metadata fields match the supplied keyword
  123. arguments, as an instance of :class:`~gridfs.grid_file.GridOut`.
  124. Version numbering is a convenience atop the GridFS API provided
  125. by MongoDB. If more than one file matches the query (either by
  126. `filename` alone, by metadata fields, or by a combination of
  127. both), then version ``-1`` will be the most recently uploaded
  128. matching file, ``-2`` the second most recently
  129. uploaded, etc. Version ``0`` will be the first version
  130. uploaded, ``1`` the second version, etc. So if three versions
  131. have been uploaded, then version ``0`` is the same as version
  132. ``-3``, version ``1`` is the same as version ``-2``, and
  133. version ``2`` is the same as version ``-1``.
  134. Raises :class:`~gridfs.errors.NoFile` if no such version of
  135. that file exists.
  136. An index on ``{filename: 1, uploadDate: -1}`` will
  137. automatically be created when this method is called the first
  138. time.
  139. :Parameters:
  140. - `filename`: ``"filename"`` of the file to get, or `None`
  141. - `version` (optional): version of the file to get (defaults
  142. to -1, the most recent version uploaded)
  143. - `**kwargs` (optional): find files by custom metadata.
  144. """
  145. self.__ensure_index_filename()
  146. query = kwargs
  147. if filename is not None:
  148. query["filename"] = filename
  149. cursor = self.__files.find(query)
  150. if version < 0:
  151. skip = abs(version) - 1
  152. cursor.limit(-1).skip(skip).sort("uploadDate", DESCENDING)
  153. else:
  154. cursor.limit(-1).skip(version).sort("uploadDate", ASCENDING)
  155. try:
  156. grid_file = next(cursor)
  157. return GridOut(self.__collection, file_document=grid_file)
  158. except StopIteration:
  159. raise NoFile("no version %d for filename %r" % (version, filename))
  160. def get_last_version(self, filename=None, **kwargs):
  161. """Get the most recent version of a file in GridFS by ``"filename"``
  162. or metadata fields.
  163. Equivalent to calling :meth:`get_version` with the default
  164. `version` (``-1``).
  165. :Parameters:
  166. - `filename`: ``"filename"`` of the file to get, or `None`
  167. - `**kwargs` (optional): find files by custom metadata.
  168. """
  169. return self.get_version(filename=filename, **kwargs)
  170. # TODO add optional safe mode for chunk removal?
  171. def delete(self, file_id):
  172. """Delete a file from GridFS by ``"_id"``.
  173. Deletes all data belonging to the file with ``"_id"``:
  174. `file_id`.
  175. .. warning:: Any processes/threads reading from the file while
  176. this method is executing will likely see an invalid/corrupt
  177. file. Care should be taken to avoid concurrent reads to a file
  178. while it is being deleted.
  179. .. note:: Deletes of non-existent files are considered successful
  180. since the end result is the same: no file with that _id remains.
  181. :Parameters:
  182. - `file_id`: ``"_id"`` of the file to delete
  183. """
  184. self.__ensure_index_files_id()
  185. self.__files.delete_one({"_id": file_id})
  186. self.__chunks.delete_many({"files_id": file_id})
  187. def list(self):
  188. """List the names of all files stored in this instance of
  189. :class:`GridFS`.
  190. An index on ``{filename: 1, uploadDate: -1}`` will
  191. automatically be created when this method is called the first
  192. time.
  193. .. versionchanged:: 2.7
  194. ``list`` ensures an index, the same as ``get_version``.
  195. """
  196. self.__ensure_index_filename()
  197. # With an index, distinct includes documents with no filename
  198. # as None.
  199. return [
  200. name for name in self.__files.distinct("filename")
  201. if name is not None]
  202. def find_one(self, filter=None, *args, **kwargs):
  203. """Get a single file from gridfs.
  204. All arguments to :meth:`find` are also valid arguments for
  205. :meth:`find_one`, although any `limit` argument will be
  206. ignored. Returns a single :class:`~gridfs.grid_file.GridOut`,
  207. or ``None`` if no matching file is found. For example::
  208. file = fs.find_one({"filename": "lisa.txt"})
  209. :Parameters:
  210. - `filter` (optional): a dictionary specifying
  211. the query to be performing OR any other type to be used as
  212. the value for a query for ``"_id"`` in the file collection.
  213. - `*args` (optional): any additional positional arguments are
  214. the same as the arguments to :meth:`find`.
  215. - `**kwargs` (optional): any additional keyword arguments
  216. are the same as the arguments to :meth:`find`.
  217. """
  218. if filter is not None and not isinstance(filter, Mapping):
  219. filter = {"_id": filter}
  220. for f in self.find(filter, *args, **kwargs):
  221. return f
  222. return None
  223. def find(self, *args, **kwargs):
  224. """Query GridFS for files.
  225. Returns a cursor that iterates across files matching
  226. arbitrary queries on the files collection. Can be combined
  227. with other modifiers for additional control. For example::
  228. for grid_out in fs.find({"filename": "lisa.txt"},
  229. no_cursor_timeout=True):
  230. data = grid_out.read()
  231. would iterate through all versions of "lisa.txt" stored in GridFS.
  232. Note that setting no_cursor_timeout to True may be important to
  233. prevent the cursor from timing out during long multi-file processing
  234. work.
  235. As another example, the call::
  236. most_recent_three = fs.find().sort("uploadDate", -1).limit(3)
  237. would return a cursor to the three most recently uploaded files
  238. in GridFS.
  239. Follows a similar interface to
  240. :meth:`~pymongo.collection.Collection.find`
  241. in :class:`~pymongo.collection.Collection`.
  242. :Parameters:
  243. - `filter` (optional): a SON object specifying elements which
  244. must be present for a document to be included in the
  245. result set
  246. - `skip` (optional): the number of files to omit (from
  247. the start of the result set) when returning the results
  248. - `limit` (optional): the maximum number of results to
  249. return
  250. - `no_cursor_timeout` (optional): if False (the default), any
  251. returned cursor is closed by the server after 10 minutes of
  252. inactivity. If set to True, the returned cursor will never
  253. time out on the server. Care should be taken to ensure that
  254. cursors with no_cursor_timeout turned on are properly closed.
  255. - `sort` (optional): a list of (key, direction) pairs
  256. specifying the sort order for this query. See
  257. :meth:`~pymongo.cursor.Cursor.sort` for details.
  258. Raises :class:`TypeError` if any of the arguments are of
  259. improper type. Returns an instance of
  260. :class:`~gridfs.grid_file.GridOutCursor`
  261. corresponding to this query.
  262. .. versionchanged:: 3.0
  263. Removed the read_preference, tag_sets, and
  264. secondary_acceptable_latency_ms options.
  265. .. versionadded:: 2.7
  266. .. mongodoc:: find
  267. """
  268. return GridOutCursor(self.__collection, *args, **kwargs)
  269. def exists(self, document_or_id=None, **kwargs):
  270. """Check if a file exists in this instance of :class:`GridFS`.
  271. The file to check for can be specified by the value of its
  272. ``_id`` key, or by passing in a query document. A query
  273. document can be passed in as dictionary, or by using keyword
  274. arguments. Thus, the following three calls are equivalent:
  275. >>> fs.exists(file_id)
  276. >>> fs.exists({"_id": file_id})
  277. >>> fs.exists(_id=file_id)
  278. As are the following two calls:
  279. >>> fs.exists({"filename": "mike.txt"})
  280. >>> fs.exists(filename="mike.txt")
  281. And the following two:
  282. >>> fs.exists({"foo": {"$gt": 12}})
  283. >>> fs.exists(foo={"$gt": 12})
  284. Returns ``True`` if a matching file exists, ``False``
  285. otherwise. Calls to :meth:`exists` will not automatically
  286. create appropriate indexes; application developers should be
  287. sure to create indexes if needed and as appropriate.
  288. :Parameters:
  289. - `document_or_id` (optional): query document, or _id of the
  290. document to check for
  291. - `**kwargs` (optional): keyword arguments are used as a
  292. query document, if they're present.
  293. """
  294. if kwargs:
  295. return self.__files.find_one(kwargs, ["_id"]) is not None
  296. return self.__files.find_one(document_or_id, ["_id"]) is not None