
    9h I                         S r SSKrSSKrSSKrSSKrSSKrSSKJrJr  SSKJ	r	  SSK
JrJrJr  SSKJrJrJrJrJrJr   " S S\5      r " S	 S
\5      r " S S5      r " S S5      r " S S5      rS rg)zDGridFS implementation for Motor, an asynchronous driver for MongoDB.    N)DEFAULT_CHUNK_SIZE	grid_file)
docstrings)AgnosticCollectionAgnosticCursorAgnosticDatabase)AsyncCommand	AsyncReadDelegateMethodReadOnlyPropertycoroutine_annotationcreate_class_with_frameworkc                   D   ^  \ rS rSrSr\R                  rU 4S jrSr	U =r
$ )AgnosticGridOutCursor$   MotorGridOutCursorc                    > [         TU ]  5       nU(       a6  [        [        U R                  U R
                  5      nU" U R                  US9$ g)z5**DEPRECATED** - Get next GridOut object from cursor.)delegateN)supernext_objectr   AgnosticGridOut
_framework
__module__
collection)selfgrid_outgrid_out_class	__class__s      WC:\Suresh\moveshuttle\MDcreated\moveengine\venv\Lib\site-packages\motor/motor_gridfs.pyr   !AgnosticGridOutCursor.next_object(   sF     7&(8$//N "$//HEE      )__name__r   __qualname____firstlineno____motor_class_name__gridfsGridOutCursor__delegate_class__r   __static_attributes____classcell__)r   s   @r   r   r   $   s    /-- r!   r   c                       \ rS rSrSrS rSrg)MotorGridOutProperty7   z<Creates a readonly attribute on the wrapped PyMongo GridOut.c                 b   ^ U4S jn[        UR                  T5      R                  n[        X4S9$ )Nc                    > U R                   R                  (       d"  [        R                  R	                  ST-  5      e[        U R                   T5      $ NzBYou must call MotorGridOut.open() before accessing the %s propertyr   _filepymongoerrorsInvalidOperationgetattr)obj	attr_names    r   fget3MotorGridOutProperty.create_attribute.<locals>.fget;   sG    <<%%nn55&(12 
 3<<33r!   )r:   doc)r7   r)   __doc__property)r   clsr9   r:   r<   s     `  r   create_attribute%MotorGridOutProperty.create_attribute:   s-    	4 c,,i8@@T++r!   r"   N)r#   r   r$   r%   r=   r@   r*   r"   r!   r   r-   r-   7   s
    F,r!   r-   c                   v   \ rS rSrSrSr\R                  r\	" 5       r
\	" 5       r\	" 5       r\	" 5       r\	" 5       r\	" 5       r\	" 5       r\	" 5       r\	" 5       r\" SS9r\" 5       r\" 5       r\" 5       r\" 5       r\" 5       r\" 5       r\" 5       r\	" 5       r\" 5       r SS jr S r!S	 r"S
 r#\$S 5       r%S r&S r'Sr(g)r   H   a  Class to read data out of GridFS.

MotorGridOut supports the same attributes as PyMongo's
:class:`~gridfs.grid_file.GridOut`, such as ``_id``, ``content_type``,
etc.

You don't need to instantiate this class directly - use the
methods provided by :class:`~motor.MotorGridFSBucket`. If it **is**
instantiated directly, call :meth:`open`, :meth:`read`, or
:meth:`readline` before accessing its attributes.
MotorGridOutopen)r9   Nc                    [        [        U R                  U R                  5      n[	        X5      (       d  [        SU-  5      eU(       a  X@l        O U R                  UR                  X#US9U l        UR                  5       U l	        g )Nz>First argument to MotorGridOut must be MotorCollection, not %r)session)
r   r   r   r   
isinstance	TypeErrorr   r)   get_io_loopio_loop)r   root_collectionfile_idfile_documentr   rG   collection_classs          r   __init__AgnosticGridOut.__init__l   s     7
 /<<*,;< 
 $M 33(('' 4 DM '224r!   c                     U $ Nr"   r   s    r   	__aiter__AgnosticGridOut.__aiter__   s    r!   c                 d   #    U R                  5       I S h  vN nU(       a  U$ [        5       e N7frS   )	readchunkStopAsyncIteration)r   chunks     r   	__anext__AgnosticGridOut.__anext__   s*     nn&&L "" 's   0.0c                     U R                   R                  (       d"  [        R                  R	                  SU-  5      e[        U R                   U5      $ r1   r2   )r   items     r   __getattr__AgnosticGridOut.__getattr__   sB    }}""..11TW[[  t}}d++r!   c                 t    U R                   R                  U R                  5       U R                  5       U 5      $ )a  Retrieve this file's attributes from the server.

Returns a Future.

.. versionchanged:: 2.0
   No longer accepts a callback argument.

.. versionchanged:: 0.2
   :class:`~motor.MotorGridOut` now opens itself on demand, calling
   ``open`` explicitly is rarely needed.
)r   chain_return_value_openrJ   rT   s    r   rE   AgnosticGridOut.open   s-     11$**,@P@P@RTXYYr!   c                     U R                   $ rS   rK   rT   s    r   rJ   AgnosticGridOut.get_io_loop       ||r!   c                    #    SnX R                   :  ad  U R                  U R                  5      I Sh  vN nUR                  U5        UR	                  5         U[        U5      -  nX R                   :  a  Mc  gg NF7f)a  Write the contents of this file to a
:class:`tornado.web.RequestHandler`. This method calls
:meth:`~tornado.web.RequestHandler.flush` on
the RequestHandler, so ensure all headers have already been set.
For a more complete example see the implementation of
:class:`~motor.web.GridFSHandler`.

.. code-block:: python

    class FileHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        @gen.coroutine
        def get(self, filename):
            db = self.settings["db"]
            fs = await motor.MotorGridFSBucket(db())
            try:
                gridout = await fs.open_download_stream_by_name(filename)
            except gridfs.NoFile:
                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", gridout.content_type)
            self.set_header("Content-Length", gridout.length)
            await gridout.stream_to_handler(self)
            self.finish()

.. seealso:: Tornado `RequestHandler <http://tornadoweb.org/en/stable/web.html#request-handlers>`_
r   N)lengthread
chunk_sizewriteflushlen)r   request_handlerwrittenrZ   s       r   stream_to_handler!AgnosticGridOut.stream_to_handler   sd     8 #))DOO44E !!%(!!#s5z!G #4s   0A;A9AA;7A;r   rK   )NNNN))r#   r   r$   r%   r=   r&   r'   GridOutr)   r-   _idaliasesrl   closecontent_typefilenamerj   metadatanamer	   rc   r
   rk   r   readablerX   readlineseekseekabletellupload_daterm   rP   rU   r[   r_   r   rE   rJ   rr   r*   r"   r!   r   r   r   H   s    
 *

 C"$G%'J "E')L#%H!#F#%H!D6*E;DHI{HDHD&(KE Y]5,#, Z Z%"r!   r   c                      \ rS rSrSr\R                  r\" 5       r	\
" 5       r\" 5       r\
" 5       r\
" 5       r\" 5       r\
" 5       r\
" 5       r\
" 5       r\
" 5       r\" 5       r\" 5       r\" 5       r\
" 5       r\" 5       R3                  S5      r\" 5       r\" 5       R3                  S5      r\" S5      r\" SSS9rSS	 jrS
 r S r!S r"Sr#g)AgnosticGridIn   MotorGridInrD   __exit____setattr__a  
Set an arbitrary metadata attribute on the file. Stores value on the server
as a key-value pair within the file document once the file is closed. If
the file is already closed, calling :meth:`set` will immediately update the file
document on the server.

Metadata set on the file appears as attributes on a
:class:`~motor.MotorGridOut` object created from the file.

:Parameters:
  - `name`: Name of the attribute, will be stored as a key in the file
    document on the server
  - `value`: Value of the attribute
)r9   r<   Nc                    [        [        U R                  U R                  5      n[	        X5      (       d  [        SU-  5      eUR                  5       U l        U=(       d    U R                  " UR                  4SU0UD6U l	        g)a  
Class to write data to GridFS. Application developers should not
generally need to instantiate this class - see
:meth:`~motor.MotorGridFSBucket.open_upload_stream`.

Any of the file level options specified in the `GridFS Spec
<http://dochub.mongodb.org/core/gridfs/>`_ 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: 256 kb)

  - ``"encoding"``: encoding used for this file. In Python 2,
    any :class:`unicode` that is written to the file will be
    converted to a :class:`str`. In Python 3, any :class:`str`
    that is written to the file will be converted to
    :class:`bytes`.

:Parameters:
  - `root_collection`: root collection to write to
  - `session` (optional): a
    :class:`~pymongo.client_session.ClientSession` to use for all
    commands
  - `**kwargs` (optional): file level options (see above)

.. versionchanged:: 3.0
   Removed support for the `disable_md5` parameter (to match the
   GridIn class in PyMongo).
.. versionchanged:: 0.2
   ``open`` method removed, no longer needed.
z=First argument to MotorGridIn must be MotorCollection, not %rrG   N)
r   r   r   r   rH   rI   rJ   rK   r)   r   )r   rL   r   rG   kwargsrO   s         r   rP   AgnosticGridIn.__init__   s    V 7
 /<<ORaa  '224  
D$;$;$$%
.5%
9?%
r!   c                    #    U $ 7frS   r"   rT   s    r   
__aenter__AgnosticGridIn.__aenter__0  s
     s   c                 D   #    U R                  XU5      I S h  vN   g  N7frS   )_exit)r   exc_typeexc_valexc_tbs       r   	__aexit__AgnosticGridIn.__aexit__3  s     jjF333s     c                     U R                   $ rS   rf   rT   s    r   rJ   AgnosticGridIn.get_io_loop6  rh   r!   rt   )NN)$r#   r   r$   r%   r&   r'   GridInr)   r   r_   r   rv   r	   abortrl   closedrx   ry   rz   rj   r|   rk   r}   r   r   unwraprm   	writeable
writelinesr   setrP   r   r   rJ   r*   r"   r!   r   r   r      s    ( "K

CNE!#JFNE#%L!HFDDHH"$KN!!.1E I&&~6J$E
C$8
v4r!   r   c                   ^   \ rS rSrSr\R                  r\" \	R                  S9r\" \	R                  S9r\" \	R                  S9r\" \	R                   S9R#                  \R$                  5      r\" \	R(                  S9R#                  \R$                  5      r\" \	R.                  S9R#                  \R0                  5      r\" \	R4                  S9R#                  \R0                  5      r\" \	R8                  S9r\" \	R<                  S9r\" \	R@                  S9r!S\"SSS4S jr#S r$S rS	 r%S
r&g)AgnosticGridFSBucketi:  MotorGridFSBucket)r<   fsNc                 |   Ub  [         R                  " S[        SS9  Un[        [        U R
                  U R                  5      n[        X5      (       d  [        SU R                   SU< 35      eUR                  5       U l        UR                  X$US9U l        U R                  UR                  UUUUS9U l        g)	a"  Create a handle to a GridFS bucket.

Raises :exc:`~pymongo.errors.ConfigurationError` if `write_concern`
is not acknowledged.

This class conforms to the `GridFS API Spec
<https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst>`_
for MongoDB drivers.

: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.
  - `collection` (optional): Deprecated, an alias for `bucket_name`
    that exists solely to provide backwards compatibility.

.. versionchanged:: 3.0
   Removed support for the `disable_md5` parameter (to match the
   GridFSBucket class in PyMongo).
.. versionchanged:: 2.1
   Added support for the `bucket_name`, `chunk_size_bytes`,
   `write_concern`, and `read_preference` parameters.
   Deprecated the `collection` parameter which is now an alias to
   `bucket_name` (to match the GridFSBucket class in PyMongo).
.. versionadded:: 1.0

.. mongodoc:: gridfs
NzCthe "collection" parameter is deprecated, use "bucket_name" instead   )
stacklevelzFirst argument to z must be  MotorDatabase, not )write_concernread_preference)chunk_size_bytesr   r   )warningswarnDeprecationWarningr   r   r   r   rH   rI   r   rJ   rK   get_collectionr   r)   r   )r   databasebucket_namer   r   r   r   db_classs           r   rP   AgnosticGridFSBucket.__init__Q  s    X !MMU"
 %K./?RVRaRab(--$T^^$44QRZQ]^   ++-"11o 2 
 //-'+ 0 
r!   c                     U R                   $ rS   rf   rT   s    r   rJ    AgnosticGridFSBucket.get_io_loop  rh   r!   c                    UR                   [        R                  L a6  [        [        U R
                  U R                  5      nU" U R                  US9$ UR                   [        R                  L a6  [        [        U R
                  U R                  5      nU" U R                  US9$ UR                   [        R                  L a5  [        [        U R
                  U R                  5      nU" XR                  S9$ g )N)rL   r   )cursorr   )r   r   r   r   r   r   r   r   ru   r   r'   r(   r   )r   r8   grid_in_classr   s       r   wrapAgnosticGridFSBucket.wrap  s    ==I,,,7M !3OO]]i///8$//N "$//CPP]]f2228%tN "II 3r!   c                     U R                   R                  " U0 UD6n[        [        U R                  U R
                  5      nU" X0R                  5      $ )a  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::

  cursor = bucket.find({"filename": "lisa.txt"}, no_cursor_timeout=True)
  while (await cursor.fetch_next):
      grid_out = cursor.next_object()
      data = await grid_out.read()

This iterates 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:`~motor.MotorCollection.find`
in :class:`~motor.MotorCollection`.

: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.
  - `session` (optional): a
    :class:`~pymongo.client_session.ClientSession`, created with
    :meth:`~MotorClient.start_session`.

If a :class:`~pymongo.client_session.ClientSession` is passed to
:meth:`find`, all returned :class:`MotorGridOut` instances
are associated with that session.

.. versionchanged:: 1.2
   Added session parameter.
)r   findr   r   r   r   r   )r   argsr   r   grid_out_cursors        r   r   AgnosticGridFSBucket.find  sH    j ##T4V45!4??DOO
 v77r!   )r   r   rK   )'r#   r   r$   r%   r&   r'   GridFSBucketr)   r	   r   gridfs_delete_docdeletegridfs_download_to_stream_docdownload_to_stream%gridfs_download_to_stream_by_name_docdownload_to_stream_by_namegridfs_open_download_stream_docr   ru   open_download_stream'gridfs_open_download_stream_by_name_docopen_download_stream_by_namer   gridfs_open_upload_stream_docr   open_upload_stream%gridfs_open_upload_stream_with_id_docopen_upload_stream_with_idgridfs_rename_docrenamegridfs_upload_from_stream_docupload_from_stream%gridfs_upload_from_stream_with_id_docupload_from_stream_with_idr   rP   rJ   r   r*   r"   r!   r   r   r   :  s6   .,,j::;F%**R*RS!-*2b2b!c'J,V,VW\\ $0>>$
d6>> ! (J,T,TUZZ "0<<"
d6==  j::;F%**R*RS!-*2b2b!c
 +E
NJ,:8r!   r   c                 ^   [         R                  " [        U R                  5      R	                  S5      5      nUR                  [        U R                  5      R	                  S5      5        UR                  [        U R                  5      R	                  S5      5        UR                  5       $ )zCompute the effective hash of a GridOut object for use with an Etag header.

Create a FIPS-compliant Etag HTTP header hash using sha256
We use the _id + length + upload_date as a proxy for
uniqueness to avoid reading the entire file.
utf8)	hashlibsha256strrv   encodeupdaterj   r   	hexdigest)gridout	grid_hashs     r   _hash_gridoutr     s{     s7;;/66v>?IS(//78S,,-44V<=  r!   )r=   r   r   r'   r4   pymongo.errorsr   r   motorr   
motor.corer   r   r   motor.metaprogrammingr	   r
   r   r   r   r   r   r-   r   r   r   r   r"   r!   r   <module>r      su    K      0  K K N &,+ ,"B" B"Jj jZq8 q8h
!r!   