U
    d                     @   s   d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% dddddddgZ&G dd dZ'G dd dZ(dS )a  GridFS is a specification for storing large objects in Mongo.

The :mod:`gridfs` package is an implementation of GridFS on top of
:mod:`pymongo`, exposing a file-like interface.

.. seealso:: The MongoDB documentation on `gridfs <https://dochub.mongodb.org/core/gridfs>`_.
    )abc)AnyListMappingOptionalcast)ObjectId)NoFile)DEFAULT_CHUNK_SIZEGridInGridOutGridOutCursor_clear_entity_type_registry_disallow_transactions)	ASCENDING
DESCENDING_csot)ClientSession)
Collection)validate_string)Database)ConfigurationError)_ServerMode)WriteConcernGridFSGridFSBucketr	   r
   r   r   r   c                   @   s$  e Zd ZdZd%eedddZeedddZ	eeed	d
dZ
d&eee edddZd'ee ee ee eedddZd(ee ee eedddZd)eee ddddZd*ee ee dddZd+ee ee eeee dddZeeedd d!Zd,ee ee eed"d#d$ZdS )-r   2An instance of GridFS on top of a single Database.fs)database
collectionc                 C   sL   t |tstdt|}|jjs*td|| | _| jj| _	| jj
| _dS )a  Create a new instance of :class:`GridFS`.

        Raises :class:`TypeError` if `database` is not an instance of
        :class:`~pymongo.database.Database`.

        :Parameters:
          - `database`: database to use
          - `collection` (optional): 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 <https://dochub.mongodb.org/core/gridfs>`_.
        (database must be an instance of Databasez,database must use acknowledged write_concernN)
isinstancer   	TypeErrorr   write_concernacknowledgedr   _GridFS__collectionfiles_GridFS__fileschunks_GridFS__chunks)selfr   r    r+   3/tmp/pip-unpacked-wheel-oblwsawz/gridfs/__init__.py__init__;   s    


zGridFS.__init__)kwargsreturnc                 K   s   t | jf|S )a  Create 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.

        :Parameters:
          - `**kwargs` (optional): keyword arguments for file creation
        )r   r%   )r*   r.   r+   r+   r,   new_filee   s    zGridFS.new_file)datar.   r/   c              
   K   s6   t | jf|}|| |jW  5 Q R  S Q R X dS )a   Put data in GridFS as a new file.

        Equivalent to doing::

          with fs.new_file(**kwargs) as f:
              f.write(data)

        `data` can be either an instance of :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.

        :Parameters:
          - `data`: data to be written as a file.
          - `**kwargs` (optional): keyword arguments for file creation

        .. versionchanged:: 3.0
           w=0 writes to GridFS are now prohibited.
        N)r   r%   write_id)r*   r1   r.   	grid_filer+   r+   r,   putu   s    
z
GridFS.putNfile_idsessionr/   c                 C   s   t | j||d}|  |S )a  Get a file from GridFS by ``"_id"``.

        Returns an instance of :class:`~gridfs.grid_file.GridOut`,
        which provides a file-like interface for reading.

        :Parameters:
          - `file_id`: ``"_id"`` of the file to get
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r8   )r   r%   _ensure_filer*   r7   r8   goutr+   r+   r,   get   s    z
GridFS.get)filenameversionr8   r.   r/   c           	      K   s   |}|dk	r||d< t | | jj||d}|dkr8d}|dk rft|d }|d|dt n|d|dt zt	|}t
| j||dW S  tk
r   td	||f Y nX dS )
a(  Get a file from GridFS by ``"filename"`` or metadata fields.

        Returns a version of the file in GridFS whose filename matches
        `filename` and whose metadata fields match the supplied keyword
        arguments, as an instance of :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.

        :Parameters:
          - `filename`: ``"filename"`` of the file to get, or `None`
          - `version` (optional): version of the file to get (defaults
            to -1, the most recent version uploaded)
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`
          - `**kwargs` (optional): find files by custom metadata.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``get_version`` no longer ensures indexes.
        Nr?   r9   r>   r      
uploadDateZfile_documentr8   no version %d for filename %r)r   r'   findabslimitskipsortr   r   nextr   r%   StopIterationr	   )	r*   r?   r@   r8   r.   querycursorrH   docr+   r+   r,   get_version   s     )zGridFS.get_version)r?   r8   r.   r/   c                 K   s   | j f ||d|S )a  Get the most recent version of a file in GridFS by ``"filename"``
        or metadata fields.

        Equivalent to calling :meth:`get_version` with the default
        `version` (``-1``).

        :Parameters:
          - `filename`: ``"filename"`` of the file to get, or `None`
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`
          - `**kwargs` (optional): find files by custom metadata.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        )r?   r8   )rO   )r*   r?   r8   r.   r+   r+   r,   get_last_version   s    zGridFS.get_last_versionc                 C   s4   t | | jjd|i|d | jjd|i|d dS )a`  Delete a file from GridFS by ``"_id"``.

        Deletes all data belonging to the file with ``"_id"``:
        `file_id`.

        .. warning:: Any processes/threads reading from the file while
           this method is executing will likely see an invalid/corrupt
           file. Care should be taken to avoid concurrent reads to a file
           while it is being deleted.

        .. note:: Deletes of non-existent files are considered successful
           since the end result is the same: no file with that _id remains.

        :Parameters:
          - `file_id`: ``"_id"`` of the file to delete
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``delete`` no longer ensures indexes.
        r3   r9   files_idN)r   r'   
delete_oner)   delete_many)r*   r7   r8   r+   r+   r,   delete   s    zGridFS.delete)r8   r/   c                 C   s"   t | dd | jjd|dD S )af  List the names of all files stored in this instance of
        :class:`GridFS`.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``list`` no longer ensures indexes.
        c                 S   s   g | ]}|d k	r|qS )Nr+   ).0namer+   r+   r,   
<listcomp>'  s     zGridFS.list.<locals>.<listcomp>r?   r9   )r   r'   Zdistinct)r*   r8   r+   r+   r,   list  s    zGridFS.list)filterr8   argsr.   r/   c                 O   sN   |dk	rt |tjsd|i}t| | j|f|d|i|D ]
}|  S dS )a  Get a single file from gridfs.

        All arguments to :meth:`find` are also valid arguments for
        :meth:`find_one`, although any `limit` argument will be
        ignored. Returns a single :class:`~gridfs.grid_file.GridOut`,
        or ``None`` if no matching file is found. For example::

            file = fs.find_one({"filename": "lisa.txt"})

        :Parameters:
          - `filter` (optional): a dictionary specifying
            the query to be performing OR any other type to be used as
            the value for a query for ``"_id"`` in the file collection.
          - `*args` (optional): any additional positional arguments are
            the same as the arguments to :meth:`find`.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`
          - `**kwargs` (optional): any additional keyword arguments
            are the same as the arguments to :meth:`find`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        Nr3   r8   )r!   r   r   r   rE   )r*   rY   r8   rZ   r.   fr+   r+   r,   find_one+  s    zGridFS.find_onerZ   r.   r/   c                 O   s   t | jf||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.

        :Parameters:
          - `filter` (optional): A query document that selects which files
            to include in the result set. Can be an empty document to include
            all files.
          - `skip` (optional): the number of files to omit (from
            the start of the result set) when returning the results
          - `limit` (optional): the maximum number of results to
            return
          - `no_cursor_timeout` (optional): if False (the default), any
            returned cursor is closed by the server after 10 minutes of
            inactivity. If set to True, the returned cursor will never
            time out on the server. Care should be taken to ensure that
            cursors with no_cursor_timeout turned on are properly closed.
          - `sort` (optional): a list of (key, direction) pairs
            specifying the sort order for this query. See
            :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 <https://dochub.mongodb.org/core/find>`_.
        )r   r%   r*   rZ   r.   r+   r+   r,   rE   R  s    ;zGridFS.find)document_or_idr8   r.   r/   c                 K   s>   t | |r"| jj|dg|d}n| jj|dg|d}|dk	S )aQ  Check 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.

        :Parameters:
          - `document_or_id` (optional): query document, or _id of the
            document to check for
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`
          - `**kwargs` (optional): keyword arguments are used as a
            query document, if they're present.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   r9   N)r   r'   r\   )r*   r_   r8   r.   r[   r+   r+   r,   exists  s
    +zGridFS.exists)r   )N)Nr>   N)NN)N)N)NN)NN)__name__
__module____qualname____doc__r   strr-   r   r   r0   r5   r   r   r   r=   intrO   rP   rT   r   rX   r\   r   rE   boolr`   r+   r+   r+   r,   r   8   sV   *   =       '?  c                
   @   s  e Zd ZdZdeddfeeeee	 ee
 ddddZd(eee eeeef  ee eddd	Zd)eeee eeeef  ee ed
ddZejd*eeee eeeef  ee edddZejd+eeeee eeeef  ee ddddZd,eee edddZejd-eeee ddddZejd.eee ddddZeeedddZd/eeee edd d!Zejd0eeeee dd"d#d$Zd1eeee dd%d&d'ZdS )2r   r   r   N)dbbucket_namechunk_size_bytesr#   read_preferencer/   c                 C   s   t |tstdt|}|dk	r&|n|j}|js:td|| _|| | _| jj	j
||d| _| jjj
||d| _|| _|jjj| _dS )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.

        :Parameters:
          - `database`: database to use.
          - `bucket_name` (optional): The name of the bucket. Defaults to 'fs'.
          - `chunk_size_bytes` (optional): The chunk size in bytes. Defaults
            to 255KB.
          - `write_concern` (optional): The
            :class:`~pymongo.write_concern.WriteConcern` to use. If ``None``
            (the default) db.write_concern is used.
          - `read_preference` (optional): 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 <https://dochub.mongodb.org/core/gridfs>`_.
        r    Nz"write concern must be acknowledged)r#   rk   )r!   r   r"   r   r#   r$   r   Z_bucket_name_collectionr(   Zwith_options_chunksr&   _files_chunk_size_bytesclientoptionstimeout_timeout)r*   rh   ri   rj   r#   rk   Zwtcr+   r+   r,   r-     s$    *

  zGridFSBucket.__init__)r?   rj   metadatar8   r/   c                 C   sH   t d| ||dk	r|n| jd}|dk	r2||d< t| jfd|i|S )a  Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the filename, and can choose to add any
        additional information in the metadata field of the file document or
        modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          with fs.open_upload_stream(
                "test_file", chunk_size_bytes=4,
                metadata={"contentType": "text/plain"}) as grid_in:
              grid_in.write("data I want to store!")
          # uploaded on close

        Returns an instance of :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.

        :Parameters:
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r?   N)r?   
chunk_sizert   r8   r   ro   r   rl   )r*   r?   rj   rt   r8   optsr+   r+   r,   open_upload_stream  s    *
zGridFSBucket.open_upload_stream)r7   r?   rj   rt   r8   r/   c                 C   sJ   t d| |||dk	r|n| jd}|dk	r4||d< t| jfd|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.

        :Parameters:
          - `file_id`: The id to use for this file. The id must not have
            already been used for another file.
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r?   N)r3   r?   ru   rt   r8   rv   )r*   r7   r?   rj   rt   r8   rw   r+   r+   r,   open_upload_stream_with_id=  s    /
z'GridFSBucket.open_upload_stream_with_id)r?   sourcerj   rt   r8   r/   c              	   C   s4   | j ||||d}|| W 5 Q R X tt|jS )a  Uploads a user file to a GridFS bucket.

        Reads the contents of the user file from `source` and uploads
        it to the file `filename`. Source can be a string or file-like object.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          file_id = fs.upload_from_stream(
              "test_file",
              "data I want to store!",
              chunk_size_bytes=4,
              metadata={"contentType": "text/plain"})

        Returns the _id of the uploaded file.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `filename`: The name of the file to upload.
          - `source`: The source stream of the content to be uploaded. Must be
            a file-like object that implements :meth:`read` or a string.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r9   )rx   r2   r   r   r3   )r*   r?   rz   rj   rt   r8   ginr+   r+   r,   upload_from_streamz  s    ,zGridFSBucket.upload_from_stream)r7   r?   rz   rj   rt   r8   r/   c              	   C   s.   | j |||||d}|| W 5 Q R X dS )a3  Uploads a user file to a GridFS bucket with a custom file id.

        Reads the contents of the user file from `source` and uploads
        it to the file `filename`. Source can be a string or file-like object.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          file_id = fs.upload_from_stream(
              ObjectId(),
              "test_file",
              "data I want to store!",
              chunk_size_bytes=4,
              metadata={"contentType": "text/plain"})

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `file_id`: The id to use for this file. The id must not have
            already been used for another file.
          - `filename`: The name of the file to upload.
          - `source`: The source stream of the content to be uploaded. Must be
            a file-like object that implements :meth:`read` or a string.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r9   N)ry   r2   )r*   r7   r?   rz   rj   rt   r8   r{   r+   r+   r,   upload_from_stream_with_id  s    .    z'GridFSBucket.upload_from_stream_with_idr6   c                 C   s   t | j||d}|  |S )a5  Opens a Stream from which the application can read the contents of
        the stored file specified by file_id.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # get _id of file to read.
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          grid_out = fs.open_download_stream(file_id)
          contents = grid_out.read()

        Returns an instance of :class:`~gridfs.grid_file.GridOut`.

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :Parameters:
          - `file_id`: The _id of the file to be downloaded.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r9   )r   rl   r:   r;   r+   r+   r,   open_download_stream  s    z!GridFSBucket.open_download_stream)r7   destinationr8   r/   c              	   C   s<   | j ||d$}| }t|s"q.|| qW 5 Q R X dS )a  Downloads the contents of the stored file specified by file_id and
        writes the contents to `destination`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to read
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          # Get file to write to
          file = open('myfile','wb+')
          fs.download_to_stream(file_id, file)
          file.seek(0)
          contents = file.read()

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :Parameters:
          - `file_id`: The _id of the file to be downloaded.
          - `destination`: a file-like object implementing :meth:`write`.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r9   N)r~   	readchunklenr2   )r*   r7   r   r8   r<   chunkr+   r+   r,   download_to_stream  s
    zGridFSBucket.download_to_streamc                 C   sF   t | | jjd|i|d}| jjd|i|d |jsBtd| dS )a  Given an file_id, delete this stored file's files collection document
        and associated chunks from a GridFS bucket.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to delete
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          fs.delete(file_id)

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :Parameters:
          - `file_id`: The _id of the file to be deleted.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   r9   rQ   z0no file could be deleted because none matched %sN)r   rn   rR   rm   rS   Zdeleted_countr	   )r*   r7   r8   resr+   r+   r,   rT   $  s
    zGridFSBucket.deleter]   c                 O   s   t | jf||S )aE  Find and return the files collection documents that match ``filter``

        Returns a cursor that iterates across files matching
        arbitrary queries on the files collection. Can be combined
        with other modifiers for additional control.

        For example::

          for grid_data in fs.find({"filename": "lisa.txt"},
                                  no_cursor_timeout=True):
              data = grid_data.read()

        would iterate through all versions of "lisa.txt" stored in GridFS.
        Note that setting no_cursor_timeout to True may be important to
        prevent the cursor from timing out during long multi-file processing
        work.

        As another example, the call::

          most_recent_three = fs.find().sort("uploadDate", -1).limit(3)

        would return a cursor to the three most recently uploaded files
        in GridFS.

        Follows a similar interface to
        :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.

        :Parameters:
          - `filter`: Search query.
          - `batch_size` (optional): The number of documents to return per
            batch.
          - `limit` (optional): The maximum number of documents to return.
          - `no_cursor_timeout` (optional): The server normally times out idle
            cursors after an inactivity period (10 minutes) to prevent excess
            memory use. Set this option to True prevent that.
          - `skip` (optional): The number of documents to skip before
            returning.
          - `sort` (optional): The order by which to sort results. Defaults to
            None.
        )r   rl   r^   r+   r+   r,   rE   A  s    .zGridFSBucket.findr>   )r?   revisionr8   r/   c                 C   s   t d| d|i}t| | jj||d}|dk rXt|d }|d|dt n|d|dt	 zt
|}t| j||dW S  tk
r   td||f Y nX d	S )
a  Opens a Stream from which the application can read the contents of
        `filename` and optional `revision`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_out = fs.open_download_stream_by_name("test_file")
          contents = grid_out.read()

        Returns an instance of :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.

        :Parameters:
          - `filename`: The name of the file to read from.
          - `revision` (optional): Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
          - `session` (optional): a
            :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?   r9   r   rA   r>   rB   rC   rD   N)r   r   rn   rE   rF   rG   rH   rI   r   r   rJ   r   rl   rK   r	   )r*   r?   r   r8   rL   rM   rH   r4   r+   r+   r,   open_download_stream_by_nameq  s    (
z)GridFSBucket.open_download_stream_by_name)r?   r   r   r8   r/   c              	   C   s>   | j |||d$}| }t|s$q0|| qW 5 Q R X dS )a  Write the contents of `filename` (with optional `revision`) to
        `destination`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get file to write to
          file = open('myfile','wb')
          fs.download_to_stream_by_name("test_file", file)

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `filename`: The name of the file to read from.
          - `destination`: A file-like object that implements :meth:`write`.
          - `revision` (optional): Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
          - `session` (optional): a
            :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.
        r9   N)r   r   r   r2   )r*   r?   r   r   r8   r<   r   r+   r+   r,   download_to_stream_by_name  s
    -z'GridFSBucket.download_to_stream_by_name)r7   new_filenamer8   r/   c                 C   s@   t | | jjd|idd|ii|d}|js<td||f dS )a  Renames the stored file with the specified file_id.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to rename
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          fs.rename(file_id, "new_test_name")

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :Parameters:
          - `file_id`: The _id of the file to be renamed.
          - `new_filename`: The new name of the file.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   z$setr?   r9   z<no files could be renamed %r because none matched file_id %iN)r   rn   Z
update_oneZmatched_countr	   )r*   r7   r   r8   resultr+   r+   r,   rename  s     
 zGridFSBucket.rename)NNN)NNN)NNN)NNN)N)N)N)r>   N)r>   N)N) ra   rb   rc   rd   r
   r   re   rf   r   r   r   r-   r   r   r   r   rx   ry   r   applyr   r|   r}   r   r~   r   rT   r   rE   r   r   r   r+   r+   r+   r,   r     s   C   ;   =   0   3  !   $1     7  4   N))rd   collectionsr   typingr   r   r   r   r   Zbson.objectidr   Zgridfs.errorsr	   Zgridfs.grid_filer
   r   r   r   r   r   Zpymongor   r   r   Zpymongo.client_sessionr   Zpymongo.collectionr   Zpymongo.commonr   Zpymongo.databaser   Zpymongo.errorsr   Zpymongo.read_preferencesr   Zpymongo.write_concernr   __all__r   r   r+   r+   r+   r,   <module>   s4       