+\h$$dZddlmZddlZddlZddlZddlZddlmZddl m Z m Z m Z m Z mZmZddlmZddlmZddlmZmZmZdd lmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(m)Z)m*Z*m+Z+dd l,m-Z-dd l.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4dd l5m6Z6ddl7m8Z8m9Z9ddl:m;Z;ddlm?Z?ddl@mAZAddlBmCZCdZDd$dZEGddZFGddZGGddZHeDr ejneJZKGddeKZLGddZMGd d!ZNGd"d#e?ZOy)%z.Tools for representing files stored in GridFS.) annotationsN)abc)AnyIterableMappingNoReturnOptionalcast)Int64)ObjectId)CorruptGridFile FileExistsNoFile)_C_INDEX_CHUNK_OVERHEAD_F_INDEX _SEEK_CUR _SEEK_END _SEEK_SET_UPLOAD_BUFFER_CHUNKS_UPLOAD_BUFFER_SIZEDEFAULT_CHUNK_SIZEEMPTYNEWLN_clear_entity_type_registry_grid_in_property_grid_out_property) ASCENDING DESCENDING WriteConcern_csot)validate_string)BulkWriteErrorConfigurationErrorCursorNotFoundDuplicateKeyErrorInvalidOperationOperationFailure)_check_write_command_response)ReadPreference _ServerMode) ClientSession) Collection)Cursor)Database)nextTc8|r|jr tdyy)Nz3GridFS does not support multi-document transactions)in_transactionr'sessions _/root/niggaflix-v3/playground/venv/lib/python3.12/site-packages/gridfs/synchronous/grid_file.py_disallow_transactionsr6As 7))TUU*wceZdZdZdddZddZddZdddZ d ddZ d ddZ ddd Z ddd Z d dd Z dd Z d dd Zy)GridFS2An instance of GridFS on top of a single Database.c*t|tstdt|t |}|j j s td|||_|jj|_ |jj|_ y)aCreate a new instance of :class:`GridFS`. Raises :class:`TypeError` if `database` is not an instance of :class:`~pymongo.database.Database`. :param database: database to use :param collection: root collection to use .. versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.11 Running a GridFS operation in a transaction now always raises an error. GridFS does not support multi-document transactions. .. versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionchanged:: 3.1 Indexes are only ensured on the first write to the DB. .. versionchanged:: 3.0 `database` must use an acknowledged :attr:`~pymongo.database.Database.write_concern` .. seealso:: The MongoDB documentation on `gridfs `_. .database must be an instance of Database, not z,database must use acknowledged write_concernN) isinstancer/ TypeErrortyper write_concern acknowledgedr$ _collectionfiles_fileschunks_chunks)selfdatabase collections r5__init__zGridFS.__init__Is:(H-LTRZ^L\]^ ^.x8%%22$%ST T#J/&&,, ''.. r7c .t|jfi|S)aCreate a new file in GridFS. Returns a new :class:`~gridfs.grid_file.GridIn` instance to which data can be written. Any keyword arguments will be passed through to :meth:`~gridfs.grid_file.GridIn`. If the ``"_id"`` of the file is manually specified, it must not already exist in GridFS. Otherwise :class:`~gridfs.errors.FileExists` is raised. :param kwargs: keyword arguments for file creation )GridInrB)rGkwargss r5new_filezGridFS.new_filersd&&1&11r7c t|jfi|5}|j||jcdddS#1swYyxYw)aPut 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 :class:`bytes` or a file-like object providing a :meth:`read` method. If an `encoding` keyword argument is passed, `data` can also be a :class:`str` instance, which will be encoded as `encoding` before being written. Any keyword arguments will be passed through to the created file - see :meth:`~gridfs.grid_file.GridIn` 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. Otherwise :class:`~gridfs.errors.FileExists` is raised. :param data: data to be written as a file. :param kwargs: keyword arguments for file creation .. versionchanged:: 3.0 w=0 writes to GridFS are now prohibited. N)rLrBwrite_id)rGdatarM grid_files r5putz GridFS.putsA4D$$ / / !9 OOD !== ! ! !s >ANcVt|j||}|j|S)aGet a file from GridFS by ``"_id"``. Returns an instance of :class:`~gridfs.grid_file.GridOut`, which provides a file-like interface for reading. :param file_id: ``"_id"`` of the file to get :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r3GridOutrBopenrGfile_idr4gouts r5getz GridFS.gets(t'''B  r7c |}|||d<t||jj||}|d}|dkrCt|dz }|j dj |j dtn4|j dj |j dt t|}t|j||S#t$rtd ||fzdwxYw) aGet 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 :class:`~gridfs.grid_file.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. Version ``0`` will be the first version uploaded, ``1`` the second version, etc. So if three versions have been uploaded, then version ``0`` is the same as version ``-3``, version ``1`` is the same as version ``-2``, and version ``2`` is the same as version ``-1``. Raises :class:`~gridfs.errors.NoFile` if no such version of that file exists. :param filename: ``"filename"`` of the file to get, or `None` :param version: version of the file to get (defaults to -1, the most recent version uploaded) :param session: a :class:`~pymongo.client_session.ClientSession` :param kwargs: find files by custom metadata. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.1 ``get_version`` no longer ensures indexes. Nfilenamer3r uploadDate file_documentr4no version %d for filename %r)r6rDfindabslimitskipsortrrr0rWrB StopIterationr) rGr^versionr4rMquerycursorrhdocs r5 get_versionzGridFS.get_versionsP   (E* w'!!%!9 ?G Q;w  j&EV_Fw'6DDD'DVD AH r7c4t|jg|i|S)a 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 :meth:`~pymongo.collection.Collection.find` in :class:`~pymongo.collection.Collection`. If a :class:`~pymongo.client_session.ClientSession` is passed to :meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances are associated with that session. :param filter: A query document that selects which files to include in the result set. Can be an empty document to include all files. :param skip: the number of files to omit (from the start of the result set) when returning the results :param limit: the maximum number of results to return :param no_cursor_timeout: 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. :param sort: a list of (key, direction) pairs specifying the sort order for this query. See :meth:`~pymongo.cursor.Cursor.sort` for details. Raises :class:`TypeError` if any of the arguments are of improper type. Returns an instance of :class:`~gridfs.grid_file.GridOutCursor` corresponding to this query. .. versionchanged:: 3.0 Removed the read_preference, tag_sets, and secondary_acceptable_latency_ms options. .. versionadded:: 2.7 .. seealso:: The MongoDB documentation on `find `_.  GridOutCursorrBrGr~rMs r5rez GridFS.find\s tT--????r7c t||r#|jj|dg|}|duS|jj|dg|}|duS)aCheck if a file exists in this instance of :class:`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 to :meth:`exists` will not automatically create appropriate indexes; application developers should be sure to create indexes if needed and as appropriate. :param document_or_id: query document, or _id of the document to check for :param session: a :class:`~pymongo.client_session.ClientSession` :param kwargs: keyword arguments are used as a query document, if they're present. .. versionchanged:: 3.6 Added ``session`` parameter. rQr3N)r6rDr)rGdocument_or_idr4rMrs r5existsz GridFS.existssbT w'  $$VeWg$FA} $$^eWg$NA}r7)fs)rHr/rIstr)rMrreturnrL)rRrrMrrrNrZrr4Optional[ClientSession]rrW)Nr_N) r^ Optional[str]rk Optional[int]r4rrMrrrW)NN)r^rr4rrMrrrWrZrr4rrNone)r4rrz list[str]) r} Optional[Any]r4rr~rrMrrzOptional[GridOut]r~rrMrrr)rrr4rrMrrbool)__name__ __module__ __qualname____doc__rJrNrTr\rorrrwr{rrerrqr7r5r9r9Fs<'/R 2!<*#'!#+/ 9Z9Z9Z) 9Z  9Z  9Zz#'+/NN)N N  N.I8 ,!%+/&&)& &  &  &P:@|)-+/0%0)0 0  0r7r9c>eZdZdZdeddf ddZ d ddZ d ddZej d ddZ ej d ddZ d dd Z ej d dd Z ejddd Zejddd Zdd Z d ddZej d d dZ d d!dZ d d"dZy)# GridFSBucketr:rNct|tstdt|t |}||n |j }|j s td||_|||_ |jjj|||_ |jjj|||_||_|j j"j$|_y)a!Create a new instance of :class:`GridFSBucket`. Raises :exc:`TypeError` if `database` is not an instance of :class:`~pymongo.database.Database`. Raises :exc:`~pymongo.errors.ConfigurationError` if `write_concern` is not acknowledged. :param database: database to use. :param bucket_name: The name of the bucket. Defaults to 'fs'. :param chunk_size_bytes: The chunk size in bytes. Defaults to 255KB. :param write_concern: The :class:`~pymongo.write_concern.WriteConcern` to use. If ``None`` (the default) db.write_concern is used. :param read_preference: The read preference to use. If ``None`` (the default) db.read_preference is used. .. versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.11 Running a GridFSBucket operation in a transaction now always raises an error. GridFSBucket does not support multi-document transactions. .. versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionadded:: 3.1 .. seealso:: The MongoDB documentation on `gridfs `_. r<Nz"write concern must be acknowledged)r@read_preference)r=r/r>r?rr@rAr$ _bucket_namerBrE with_optionsrFrCrD_chunk_size_bytesclientoptionstimeout_timeout)rGdb bucket_namechunk_size_bytesr@rwtcs r5rJzGridFSBucket.__init__sR"h'LTRTXJWX X ( ,,8mb>N>N$%IJ J'k?#'#3#3#:#:#G#G'$H$  #'"2"2"8"8"E"E'#F#  "2 ))11 r7c~td||||n |jd}|||d<t|jfd|i|S)aOpens 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 :class:`~gridfs.grid_file.GridIn`. Raises :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` if `filename` is not a string. :param filename: The name of the file to upload. :param chunk_size_bytes` (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`. :param metadata: 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. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r^)r^ chunk_sizemetadatar4r"rrLrB)rGr^rrr4optss r5open_upload_streamzGridFSBucket.open_upload_stream sYR  H-!$4$@ dF\F\   'D d&&@@4@@r7ctd|||||n |jd}|||d<t|jfd|i|S)a: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 :class:`~gridfs.grid_file.GridIn`. Raises :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` if `filename` is not a string. :param file_id: The id to use for this file. The id must not have already been used for another file. :param filename: The name of the file to upload. :param chunk_size_bytes` (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`. :param metadata: 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. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r^)rQr^rrr4r)rGrZr^rrr4rs r5open_upload_stream_with_idz'GridFSBucket.open_upload_stream_with_idCs\\  H- $4$@ dF\F\    'D d&&@@4@@r7c|j||||5}|j|dddttjS#1swY#xYw)aUploads 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 :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` if `filename` is not a string. :param filename: The name of the file to upload. :param source: The source stream of the content to be uploaded. Must be a file-like object that implements :meth:`read` or a string. :param chunk_size_bytes` (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`. :param metadata: 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. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r3N)rrPr r rQ)rGr^sourcerrr4gins r5upload_from_streamzGridFSBucket.upload_from_streamsUV $ $X/?SZ $ [ _b IIf  Hcgg&&  s A  Ac||j|||||5}|j|dddy#1swYyxYw)aUploads 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 :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` if `filename` is not a string. :param file_id: The id to use for this file. The id must not have already been used for another file. :param filename: The name of the file to upload. :param source: The source stream of the content to be uploaded. Must be a file-like object that implements :meth:`read` or a string. :param chunk_size_bytes` (options): The number of bytes per chunk of this file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`. :param metadata: 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. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r3N)rrP)rGrZr^rrrr4rs r5upload_from_stream_with_idz'GridFSBucket.upload_from_stream_with_idsHZ , , X/7-    IIf    s2;cVt|j||}|j|S)aOpens 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 :class:`~gridfs.grid_file.GridOut`. Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists. :param file_id: The _id of the file to be downloaded. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r3rVrYs r5open_download_streamz!GridFSBucket.open_download_streams(4t'''B  r7c|j||5} |j}t|sn|j|. dddy#1swYyxYw)apDownloads 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 :exc:`~gridfs.errors.NoFile` if no file with file_id exists. :param file_id: The _id of the file to be downloaded. :param destination: a file-like object implementing :meth:`write`. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. r3N)r readchunklenrP)rGrZ destinationr4r[chunks r5download_to_streamzGridFSBucket.download_to_streams_: & &w & @ )D(5z!!%(   ) ) )s 0AAct||jjd|i|}|jj d|i||j st d|zy)aGiven 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 :exc:`~gridfs.errors.NoFile` if no file with file_id exists. :param file_id: The _id of the file to be deleted. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. rQr3rtz0no file could be deleted because none matched %sN)r6rDrurFrv deleted_countr)rGrZr4ress r5rwzGridFSBucket.delete%se, w'kk$$eW%5w$G   *g!6 H  KgUV V!r7cDt||jjd|iddi|}|Dcgc]}|d }}|jjdd|ii|}|jjdd|ii||j st d|ycc}w) aSGiven a filename, delete this stored file's files collection document(s) and associated chunks from a GridFS bucket. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) fs.upload_from_stream("test_file", "data I want to store!") fs.delete_by_name("test_file") Raises :exc:`~gridfs.errors.NoFile` if no file with the given filename exists. :param filename: The name of the file to be deleted. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionadded:: 4.12 r^rQr`r3z$inrtz7no file could be deleted because none matched filename N)r6rDrervrFrr)rGr^r4rCfilefile_idsrs r5delete_by_namezGridFSBucket.delete_by_nameAs& w'   *h!7%W U,12DDK22kk%%uuh.?&@'%R   *uh.?!@' R  RS[R^_` `!3s Bc4t|jg|i|S)aFind 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 :meth:`~pymongo.collection.Collection.find` in :class:`~pymongo.collection.Collection`. If a :class:`~pymongo.client_session.ClientSession` is passed to :meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances are associated with that session. :param filter: Search query. :param batch_size: The number of documents to return per batch. :param limit: The maximum number of documents to return. :param no_cursor_timeout: 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. :param skip: The number of documents to skip before returning. :param sort: The order by which to sort results. Defaults to None. rrs r5rezGridFSBucket.find\s ZT--????r7ctd|d|i}t||jj||}|dkrCt |dz }|j dj |jdtn4|j dj |jdt t|}t|j||S#t$rtd||fzd wxYw) aOpens 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 :class:`~gridfs.grid_file.GridOut`. Raises :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` filename is not a string. :param filename: The name of the file to read from. :param revision: Which revision (documents with the same filename and different uploadDate) of the file to retrieve. Defaults to -1 (the most recent revision). :param session: a :class:`~pymongo.client_session.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 .. versionchanged:: 3.6 Added ``session`` parameter. r^r3rr`r_rarbrdN)r"r6rDrerfrgrhrirrr0rWrBrjr)rGr^revisionr4rlrmrhrSs r5open_download_stream_by_namez)GridFSBucket.open_download_stream_by_namesN  H-X&w'!!%!9 a<x=1$D LL  ! !$ ' , ,\: F LL  ! !( + 0 0y I [V I4++9gV V [8Hh;OOPVZ Z [s 6"CC4c|j|||5} |j}t|sn|j|. dddy#1swYyxYw)aWrite 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 :exc:`~gridfs.errors.NoFile` if no such version of that file exists. Raises :exc:`~ValueError` if `filename` is not a string. :param filename: The name of the file to read from. :param destination: A file-like object that implements :meth:`write`. :param revision: Which revision (documents with the same filename and different uploadDate) of the file to retrieve. Defaults to -1 (the most recent revision). :param session: a :class:`~pymongo.client_session.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 .. versionchanged:: 3.6 Added ``session`` parameter. r3N)rrrrP)rGr^rrr4r[rs r5download_to_stream_by_namez'GridFSBucket.download_to_stream_by_namescX . .x7 . S )W[(5z!!%(   ) ) )s 0AAct||jjd|idd|ii|}|jst d||fzy)aRenames 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 :exc:`~gridfs.errors.NoFile` if no file with file_id exists. :param file_id: The _id of the file to be renamed. :param new_filename: The new name of the file. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionchanged:: 3.6 Added ``session`` parameter. rQ$setr^r3z? $r7ct||jjd|idd|ii|}|jst d|d|y)aWRenames the stored file with the specified filename. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) fs.upload_from_stream("test_file", "data I want to store!") fs.rename_by_name("test_file", "new_test_name") Raises :exc:`~gridfs.errors.NoFile` if no file with the given filename exists. :param filename: The filename of the file to be renamed. :param new_filename: The new name of the file. :param session: a :class:`~pymongo.client_session.ClientSession` .. versionadded:: 4.12 r^rr3zno files could be renamed z because none matched filename N)r6rD update_manyrr)rGr^rr4rs r5rename_by_namezGridFSBucket.rename_by_namesm( w'((  "Vj,-G$HRY) ##,\,<<[\d[gh $r7) rr/rrrintr@zOptional[WriteConcern]rzOptional[_ServerMode]rrNNN) r^rrrrOptional[Mapping[str, Any]]r4rrrL) rZrr^rrrrrr4rrrL) r^rrrrrrrr4rrr )rZrr^rrrrrrrr4rrrrr)rZrrrr4rrrr)r^rr4rrrr)r_N)r^rrrr4rrrW) r^rrrrrr4rrr)rZrrrr4rrr)r^rrrr4rrr)rrrrrrJrrr!applyrrrrrwrrerrrrrqr7r5rrs*<  20415 =2 =2=2 =2 . =2 / =2 =2D+/04+/ 4A4A(4A. 4A ) 4A  4At+/04+/ :A:A:A( :A . :A ) :A :Ax [[ +/04+/ -'-'-'( -' . -' ) -' -'-'^ [[ +/04+//// / ( / . /)/ //d@D%< @ [[QU!)!)),!)7N!) !)!)F [[WW6 [[aa4-@`UY4[4['*4[:Q4[ 4[l [[ +/ 0)0)0) 0) ) 0)  0)0)fSW*-8O DTX+.9P r7rceZdZUdZ d: d;dZdd Z e d d d Z de d <e ddZ de d<e ddZde d<e ddZde d<e ddd Zde d<e ddd Zde d<e ddd Zde d <e d!d"d Zde d!<d#e d$<de d%<d&e d'<de d(<d?d)Zd@d*Zd@d+ZdAdBd,ZdAdCd-ZdDd.ZdEd/Zd=d0ZdFdGd1Zd>d2Zd>d3ZdHd4ZdId5Z dJd6Z!d>d7Z"dKd8Z#dLd9Z$y)MrLzClass to write data to GridFS.Nrc t|tstdt||jj s t dt|d|vr|jd|d<d|vr|jd|d<t|tj}|jdt|d<|jdt|d<tj!|d |tj!|d |tj!|d |j"tj!|d |tj!|d t%j&tj!|ddtj!|ddtj!|ddtj!|ddtj!|dgtj!|ddy)a}Write a file to GridFS Application developers should generally not need to instantiate this class directly - instead see the methods provided by :class:`~gridfs.GridFS`. Raises :class:`TypeError` if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. 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: :class:`~bson.objectid.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. Any :class:`str` that is written to the file will be converted to :class:`bytes`. :param root_collection: root collection to write to :param session: a :class:`~pymongo.client_session.ClientSession` to use for all commands :param kwargs: Any: file level options (see above) .. versionchanged:: 4.0 Removed the `disable_md5` parameter. See :ref:`removed-gridfs-checksum` for details. .. versionchanged:: 3.7 Added the `disable_md5` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 `root_collection` must use an acknowledged :attr:`~pymongo.collection.Collection.write_concern` 7root_collection must be an instance of Collection, not z3root_collection must use acknowledged write_concern content_type contentTyper chunkSize)rrQ_session_collrF_file_buffer _positionr _chunk_number_closedF_ensured_index_buffered_docs_buffered_docs_sizeN)r=r-r>r?r@rAr$r6poprr*PRIMARYr\r robject __setattr__rEioBytesIO)rGroot_collectionr4rMcolls r5rJzGridIn.__init__6sp/:6I$J_I`a ,,99$%Z[ [w' V #$*JJ~$>F= ! 6 !"(**\":F; *?NLbLbc 5(*5u $jj6HI{4W54$/4DKK84&14BJJL94a04!44E24!1594!1264!6:r7rc0|jddi|j}|_ |j|jDcgc]}|d }}||vr-|j |j ||jyyycc}w#t$rg}YEwxYw)NrQr`) projectionr4r3key)uniquer4)rr list_indexesr( create_indexitems)rGrI index_keyrrn index_spec index_keyss r5 _create_indexzGridIn._create_indexs!!eQZ!O ; '1&=&=dmm&=&T"u%   *'' (9&RVR_R_'`+ $   s#B B BB BBc6tj|dst|j|j |j j td|j |j jtdtj|ddyy)NrFT) r__getattribute__r6rrrrCrrErrrGs r5_ensure_indexeszGridIn._ensure_indexesso&&t-=> "4== 1   tzz//5 A   tzz00(D A   t%5t < ?r7c2|jjjd|jdi|j|jj j d|jdi|jtj|ddy)z>Remove all chunks/files that may have been uploaded and close.rtrQr3rTN) rrErvrrrCrurrrs r5abortz GridIn.abortsr %%z4::e3D&Et}}%] ##UDJJu,=$> #V4D1r7c|jS)zIs this file closed?)rrs r5closedz GridIn.closeds||r7rQ"The ``'_id'`` value for this file.T) read_onlyr^Name of this file.rAlias for `filename`.rzrDDEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file.rlengthLength (in bytes) of this file.) closed_onlyrrChunk size for this file.rraz!Date that this file was uploaded.datetime.datetime upload_datemd5gDEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.z io.BytesIOrrzlist[dict[str, Any]]rrc|dk(rtj||S||jvr|j|Std|z)Nrz#GridIn object has no attribute '%s')rrrAttributeErrorrGrzs r5 __getattr__zGridIn.__getattr__sH 7?**46 6 TZZ ::d# #BTIJJr7cL||jvs||jjvrtj|||y||j|<|j rKt r:|jjjd|jdid||iiytdy)NrQrzGridIn does not support __setattr__ after being closed(). Set the attribute before closing the file or use GridIn.set() instead) __dict__ __class__rrrr_IS_SYNCrrCrrrGrzvalues r5rzGridIn.__setattr__s 4== DDNN,C,C$C   tT5 1 %DJJt ||JJ$$// 58I0JVVZ\aUbLcd(Z r7c||j|<|jr:|jjj d|jdid||iiyy)NrQr)rrrrCrrs r5setz GridIn.setsN  4 << JJ   ' ' 50A(BVdTY]D[ \ r7cx|jt||jksJ|r[|jj |j d|j |d|xjt|tzz c_|jsy|s/|jtk\st|jtk\r@ |jj|j|jg|_d |_|xj d z c_|xj&t|z c_y#t$rv}|jd}|D]4}|j!ddvs|j#|j d6d|i}|jd}|r|d |d <t%|d}~wwxYw) zFlush `data` to a chunk.rQ)rtnrRNr3 writeErrorscode)i*i*i&1writeConcernErrorsr_writeConcernErrorrr`)rrrrappendrrrrrrrF insert_manyrr#detailsr\_raise_file_existsr)r)rGrRforceexc write_errorserrrwcess r5 _flush_datazGridIn._flush_datas 4yDOO+++     & &!ZZ.T5G5GQUV   $ $D O(C C $""  ''+>>4&&'+@@  (()<) zz| r7c |jdt|j|jd<tjj tj j|jd<|jjj|j|jS#t$r|j|jYywxYw)zFlush the file to the database.Tr.r )tzrar3N)r1r rrdatetimenowtimezoneutcrrC insert_onerr&r&rQrs r5_flushz GridIn._flush s .   T  *#(#8DJJx '/'8'8'<'<@Q@Q@U@U'<'VDJJ| $::##..tzz4==.Q Q  .  # #DHH - .sB3B66$CCctd|z)z3Raise a FileExists exception for the given file_id.zfile with _id %r already exists)r)rGrZs r5r&zGridIn._raise_file_existss:WDEEr7cl|js(|jtj|ddyy)zFlush the file and close it. A closed file cannot be written any more. Calling :meth:`close` more than once is allowed. rTN)rr9rrrs r5r0z GridIn.closes+ || KKM   tY 5r7c,tjd)NreadrUnsupportedOperationrGsizes r5r=z GridIn.read%s%%f--r7cyNFrqrs r5readablezGridIn.readable(r7cyrCrqrs r5seekablezGridIn.seekable+rEr7c |jr td |j}tj|r|j|y|jj!dkDrl|j"|jj!z }|r3 ||}|jj)|t+||kry|j-||j"}|rVt+||j"k(r>|j/|||j"}|rt+||j"k(r>|jj)|y#t$rt |t t fs tddt |t r6 |j|j}n#t$r tddwxYwtj|j}YwxYw#t$$r|j'wxYw)agWrite data to the file. There is no return value. `data` can be either a string of bytes or a file-like object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data` can also be a :class:`str` instance, which will be encoded as :attr:`encoding` before being written. Due to buffering, the data may not actually be written to the database until the :meth:`close` method is called. Raises :class:`ValueError` if this file is already closed. Raises :class:`TypeError` if `data` is not an instance of :class:`bytes`, a file-like object, or an instance of :class:`str`. Unicode data is only allowed if the file has an :attr:`encoding` attribute. :param data: string of bytes or file-like object to be written to the file zcannot write to a closed filez+can only write strings or file-like objectsNz7must specify an encoding for file in order to write strr)r ValueErrorr=rr=rbytesr>encodeencodingrrinspectiscoroutinefunction _write_asyncrtellr BaseExceptionrrPrr1r,)rGrRr=spaceto_writes r5rPz GridIn.write.s( <<<= = )99D  & &t ,   d #||  "Q&$,,*;*;*==#';LL&&x08}u,""$DOO,Hs8}?  *0s8}? LL  x (C )dS%L1 MNTXX$$ ;;t}}5D% #Q  ::d#((D ),) s5 EG2;G/F32G/3G  "G/.G/2H c\|jjdkDrl|j|jjz }|r3 ||}|jj |t ||kry|j||j}|rVt ||jk(r>|j|||j}|rt ||jk(r>|jj |y#t$r|j wxYwNr) rrPrrQrrPrr1r,)rGr=rRrSs r5rOzGridIn._write_asyncks <<    "OOdll&7&7&99E#E{H ""8,x=5(    (3x=DOO;   X &DOO,H3x=DOO; 8$%JJLs DD+c4|D]}|j|y)zSWrite a sequence of strings to the file. Does not add separators. N)rP)rGsequencelines r5 writelineszGridIn.writeliness  D JJt  r7cyNTrqrs r5 writeablezGridIn.writeabler7c|S)z)Support for the context manager protocol.rqrs r5 __enter__zGridIn.__enter__s r7cX||jytj|ddy)zSupport for the context manager protocol. Close the file if no exceptions occur and allow exceptions to propagate. rTF)r0rrrGexc_typeexc_valexc_tbs r5__exit__zGridIn.__exit__s1   JJL    tY 5r7r)rr-r4rrMrrr)rIr-rrrrrrrrrrrzrrr)rzrrrrr)F)rRrr'rrr)r'rrr)rr)rZrrrr_)rArrr)rRrrr)r=rrr)rWz Iterable[Any]rr)rrLrbrrcrrdrrr)%rrrrrJrrrpropertyrrrQ__annotations__r^rzrr rrrrrrr,r1r9r&r0r=rDrGrPrOrYr\r_rerqr7r5rLrL3s( ,0V;#V;)V; V;  V;p a=2 !(LX\]C]/ d?fd ZeddZded<eddZded<edd Z ded <ed d Z d ed<eddZ ded<eddZ ded<eddZ ded<eddZded<eddZded<edd Zd ed<ded!<ded"<esd#ed$<d@d%ZdAd&ZdBdCd'ZdBdDd(ZdEd)ZdFd*ZdGd+Zd@d,ZdHdId-ZdBdCd.ZdJd/ZefdKd0ZdGd1ZdLd2Z dEfd3 Z!dMd4Z"dNd5Z#dGd6Z$dLd7Z%dOd8Z&dPd9Z'dEd:Z(dGd;Z)dQdRd<Z*dEd=Z+xZ,S)SrWz!Class to read data out of GridFS.cft|tstdt|t |t |}t ||j|_ |j|_ ||_ t|_d|_d|_d|_||_||_t(sd|_yy)aRead a file from GridFS Application developers should generally not need to instantiate this class directly - instead see the methods provided by :class:`~gridfs.GridFS`. Either `file_id` or `file_document` must be specified, `file_document` will be given priority if present. Raises :class:`TypeError` if `root_collection` is not an instance of :class:`~pymongo.collection.Collection`. :param root_collection: root collection to read from :param file_id: value of ``"_id"`` for the file to read :param file_document: file document from `root_collection.files` :param session: a :class:`~pymongo.client_session.ClientSession` to use for all commands .. versionchanged:: 3.8 For better performance and to better follow the GridFS spec, :class:`GridOut` now uses a single cursor to read all the chunks in the file. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.0 Creating a GridOut does not immediately retrieve the file metadata from the server. Metadata is fetched when first needed. rrNF)r=r-r>r?r6rsuperrJrErFrCrD_file_idrr _buffer_pos _chunk_iterrrrrr)rGrrZrcr4rs r5rJzGridOut.__init__sL/:6I$J_I`a  w'5oF &-- %++   "  DKr7rQrrr^rrrrzrrrrr r rrr rraz'Date that this file was first uploaded.r raliaseszJDEPRECATED, will be removed in PyMongo 5.0. List of aliases for this file.zOptional[list[str]]rzMetadata attached to this file.rrrrrrrrc>|j}|r|Str)readlinerj)rGrXs r5__next__zGridOut.__next__s==?D / !r7c,|Dcgc]}|c}Scc}wrrq)rGxs r5to_listzGridOut.to_lists#$!A$ $$s c(|j|dS)}Read one line or up to `size` bytes from the file. :param size: the maximum number of bytes to read T)rArX_read_size_or_liner@s r5ruzGridOut.readlines **4*@ @r7cL|jg}t|j|jz }d}|dkDrh|j d}|t |z }|j |t|j|jz }d|cxkr|kr |S|dkDrh|S)r{rT)rX)rXrr rr}rr#)rGrAlines remainder bytes_readrXs r5 readlineszGridOut.readliness IIKEDKK(4>>9IJa-..D.9c$i'  T" ,t~~= t(j(L) a-Lr7c|jst|j|jj d|j i|j|_|js%t d|jd|j yy)NrQr3zno file in gridfs collection z with _id )rr6rrDrrprrs r5rXz GridOut.open"stzz "4== 1--udmm.Ddmm-\DJ::3DKK?*T]]L]^r7ctr|jn|jstd|z||jvr|j|St d|z)Nz=You must call GridOut.open() before accessing the %s propertyz$GridOut object has no attribute '%s')rrXrr'rrs r5rzGridOut.__getattr__+sY  IIK"ORVV  4:: ::d# #CdJKKr7cyr[rqrs r5rDzGridOut.readable6r]r7c|jt|j|jz }t}t |j }|dkDr|j|jd}n|jt |jkrt ||jz|z }|j't||j|j||_ |jj}|d|j|zd}|s td|xjt|z c_t|_d|_|S)z{Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned. rNrRztruncated chunk)rXrrrqrrrrr rrGridOutChunkIteratorrFrr0r )rGreceived chunk_datar chunk_numberrs r5rzGridOut.readchunk9s t||$t'7'77 ) a<d&6&6&89J ^^c$++. .4>> 9ZGHL'#7$,, |$ $$))+Evt~~ 'B'DEJ%&788 #j/) r7c|jt|j|jz }|dks||kDr|}|dk(rtSd}g}||krO||z }|j ra|j }|j }t||j d} t|_d|_|xjt| z c_n|j}d}t|} |r/|jt|||z|z } | dk\r || zdz}| dz}t| |kDr[|j| d|||_||z|_|xjt|j |j z zc_n|j| |t| z }||krO||k(r'|jr |jjdj!|S#t$rYwxYw)z&Internal read() and readline() helper.rNr`r7)rXrr rrrrq memoryviewrrrerr#rrr0rjjoin) rGrArXrrrRneededbuf chunk_startrposs r5r}zGridOut._read_size_or_lineVs  $t~~5 !8ti'D 19LoH_F||ll".. '_T-=-=-?@ $ #$ #j/1nn& '_ hhuk;3GH;V!8#c>A-D 1WF:' Jw/0" #.#7 #dll"3d6F6F"FF J' J 'H9o> 9 !1!1   %%'xx~!  s5G G,+G,c&|j|S)aRead at most `size` bytes from the file (less if there isn't enough data). The bytes are returned as an instance of :class:`bytes` If `size` is negative or omitted all data is read. :param size: the number of bytes to read .. versionchanged:: 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. )rAr|r@s r5r=z GridOut.reads&&D&11r7c|jS)z)Return the current position of this file.)rrs r5rPz GridOut.tells ~~r7c||tk(r|}nG|tk(r|j|z}n.|tk(rt |j |z}n t dd|dkr t dd||jk(r|S||_t|_d|_ |jr!|jjd|_ |S)aKSet the current position of this file. :param pos: the position (or offset if using relative positioning) to seek to :param whence: where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative to the current position, :attr:`os.SEEK_END` (``2``) to seek relative to the file's end. .. versionchanged:: 4.1 The method now returns the new position in the file, to conform to the behavior of :meth:`io.IOBase.seek`. zInvalid value for `whence`rz*Invalid value for `pos` - must be positiveN) rrrrrr OSErrorrrrqrrr0)rGrwhencenew_poss r5seekz GridOut.seeks Y G y nns*G y $++&,G":; ; Q;"JK K dnn $N         " " $#D r7cyr[rqrs r5rGzGridOut.seekabler]r7c|S)a-Return an iterator over all of this file's data. The iterator will return lines (delimited by ``b'\n'``) of :class:`bytes`. This can be useful when serving files using a webserver that handles such an iterator efficiently. .. versionchanged:: 3.8 The iterator now raises :class:`CorruptGridFile` when encountering any truncated, missing, or extra chunk in a file. The previous behavior was to only raise :class:`CorruptGridFile` on a missing chunk. .. versionchanged:: 4.0 The iterator now iterates over *lines* in the file, instead of chunks, to conform to the base class :py:class:`io.IOBase`. Use :meth:`GridOut.readchunk` to read chunk by chunk instead of line by line. rqrs r5__iter__zGridOut.__iter__s & r7c|jr!|jjd|_trt|yd|_y)z(Make GridOut more generically file-like.NT)rrr0rror)rGrs r5r0z GridOut.closes9       " " $#D   GMODKr7c,tjd)NrPr>)rGrs r5rPz GridOut.writes%%g..r7c,tjd)NrYr>)rGrs r5rYzGridOut.writeliness%%l33r7cyrCrqrs r5writablezGridOut.writablerEr7c|S)iMakes it possible to use :class:`GridOut` files with the async context manager protocol. rqrs r5r_zGridOut.__enter__s  r7c$|jy)rF)r0ras r5rezGridOut.__exit__s r7c,tjd)Nfilenor>rs r5rzGridOut.filenos%%h//r7cyrrqrs r5flushz GridOut.flushs r7cyrCrqrs r5isattyzGridOut.isattyrEr7c,tjd)Ntruncater>r@s r5rzGridOut.truncates%%j11r7cyrrqrs r5__del__zGridOut.__del__s r7r) rr-rZrrcrr4rrrrrJ)r list[bytes]ri)rArrrJ)rArrrrfrhrg)r_F)rArrXrrrJ)rr)rrrrrrrrW)rrrr)rrrrrj)rrr)rArrr)-rrrrrJrrQrlr^rzrr rrrsrrrrvryrurrXrrDrr}r=rPrrrGrr0rPrYrr_rerrrrr __classcell__rs@r5rWrWs+ "&'++/ < #< < % < ) <  < |"%)MNCN&z3GHHcH":/FGD#G"4]#L-%X/PQFCQ(6QRJR%7?&K"$6_$G -?5-H), qC J   "  % A & L:1f2 ,5%N*/4 0 2 r7rWcleZdZUdZ d dZded<d dZddZddZddZ dd Z e Z dd Z y )rzIterates over a file's chunks using a single cursor. Raises CorruptGridFile when encountering any truncated, missing, or extra chunk in a file. c:|j|_t|j|_t|j|_||_||_||_tjt|j |jz |_ d|_ yr)rQrr _chunk_sizer _lengthrFr _next_chunkmathceilfloat _num_chunks_cursor)rGgrid_outrEr4 next_chunks r5rJzGridOutChunkIterator.__init__st<<x2238??+   %99U4<<%84;K;K%KL r7zOptional[Cursor]rc||jdz kr |jS|j|j|jdz zz S)Nr`)rrr)rGchunk_ns r5expected_chunk_lengthz*GridOutChunkIterator.expected_chunk_length+sF T%%) )## #||t//43C3Ca3GHIIr7c|Srrqrs r5rzGridOutChunkIterator.__iter__0 r7cd|ji}|jdkDrd|ji|d<t|j|jj |dg|j|_y)Nrtrz$gter)rr`)rir4)rQrr6rrFrer)rGr}s r5_create_cursorz#GridOutChunkIterator._create_cursor3sadhh'   a !4#3#34F3Kt}}-||((xj$--(X r7c2|j|j|jJ |jjS#t$rG|jj |j|jjcYSwxYw)aReturn the next chunk and retry once on CursorNotFound. We retry on CursorNotFound to maintain backwards compatibility in cases where two calls to read occur more than 10 minutes apart (the server's default cursor timeout). )rrr0r%r0rs r5_next_with_retryz%GridOutChunkIterator._next_with_retry:s <<     !<<+ ++ '<<$$& & ' LL      !<<$$& & 'sAA BBc  |j}|d|jk7r-|j t d|j|dfz|d|jk\r;t |dr-|j t d|j|dfz|j|d}t |d|k7r0|j t d|d|t |dfz|xjdz c_|S#t$r4|j|jk\rt d|jzdwxYw)Nz no chunk #%drz;Missing chunk: expected chunk #%d but found chunk with n=%drRz?Extra chunk found: expected %d chunks but found chunk with n=%dzRtruncated chunk #%d: expected chunk length to be %d but found chunk with length %dr`)rrjrrr r0rr)rGrexpected_lengths r5r0zGridOutChunkIterator.nextKsl O))+E :)) ) JJL!"%)%5%5uSz$BC  :)) )5=! %&)-)9)95:(FG 44U3Z@ uV}  0 JJL!-05c OSQVW]Q^M_/`a  A = O4#3#33!.43C3C"CD$ N Os D =Ec`|jr"|jjd|_yyr)rr0rs r5r0zGridOutChunkIterator.closeps% << LL   DL r7N) rrWrEr-r4rrrrr)rrrr)rrrf)rzMapping[str, Any]) rrrrrJrlrrrrr0rvr0rqr7r5rrsl )      J Y'"!FH r7rc(eZdZddZddZddZeZy)GridOutIteratorc*t|||d|_yrU)rrr)rGrrEr4s r5rJzGridOutIterator.__init__ws/&'1Mr7c|Srrqrs r5rzGridOutIterator.__iter__zrr7cR|jj}t|dS)NrR)rrr0rJ)rGrs r5r0zGridOutIterator.next}s%  %%'U6]##r7N)rrWrEr-r4r,)rrr)rrrrJrr0rvrqr7r5rrvsN$Hr7rceZdZdZ d d fd Zd fd Zd d dZeZd dZd dZ ddZ xZ S)rzA cursor / iterator for returning GridOut objects as the result of an arbitrary query against the GridFS files collection. c t|t|}||_t ||j |||||||y)ayCreate a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. Should not be called directly by application developers - see the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead. .. versionadded 2.7 .. seealso:: The MongoDB documentation on `cursors `_. )rhrgno_cursor_timeoutri batch_sizer4N)r6r_root_collectionrorJrC) rGrIr}rhrgrrirr4rs r5rJzGridOutCursor.__init__sQ* w'0< !+     /!  r7ct|jt| }t |j ||jS)z$Get next GridOut object from cursor.rb)r6r4ror0rWr)rG next_filers r5r0zGridOutCursor.nexts3t||,GLN t,,It||\\r7c||Dcgc]}|c}S|dkr tdg}t|D]!}|j|j#|Scc}w)zConvert the cursor to a list.r`z'to_list() length must be greater than 0)rIranger#r0)rGr rxret_s r5ryzGridOutCursor.to_lists_ >#$!A$ $ A:FG Gv $A JJtyy{ # $ %s ActdNz'Method does not exist for GridOutCursorNotImplementedErrorrs r5 add_optionzGridOutCursor.add_option!"KLLr7ctdrrrs r5 remove_optionzGridOutCursor.remove_optionrr7c0t|j|S)zACreates an empty GridOutCursor for information to be copied into.r3)rr)rGr4s r5 _clone_basezGridOutCursor._clone_basesT22GDDr7)NrrFNrN)rIr-r}rrhrrgrrrrirrrr4rrrrr)r rrz list[GridOut])r~rrMrrr)r4rrr) rrrrrJr0ryrvrrrrrs@r5rrs/3"'"+/$ $ ,$  $  $  $ $ $ )$  $ L] HMMEr7r)r4rrr)Pr __future__rr4rMrr collectionsrtypingrrrrr r bson.int64r bson.objectidr gridfs.errorsr rrgridfs.grid_file_sharedrrrrrrrrrrrrrrpymongorrr r!pymongo.commonr"pymongo.errorsr#r$r%r&r'r(pymongo.helpers_sharedr)pymongo.read_preferencesr*r+"pymongo.synchronous.client_sessionr,pymongo.synchronous.collectionr-pymongo.synchronous.cursorr.pymongo.synchronous.databaser/pymongo.synchronous.helpersr0rr6r9rrLIOBaserGRIDOUT_BASE_CLASSrWrrrrqr7r5rs5" CC"== ?>*A@<5-1, V BBJ e e PhhV #+RYYn  n b a a H  FEFFEr7