class AgnosticCollection(AgnosticBase):
    __motor_class_name__ = 'MotorCollection'
    __delegate_class__ = mongomock.Collection

    bulk_write = AsyncCommand()
    count_documents = AsyncRead()
    create_index = AsyncCommand()
    create_indexes = AsyncCommand()
    delete_many = AsyncCommand()
    delete_one = AsyncCommand()
    distinct = AsyncRead()
    drop = AsyncCommand()
    drop_index = AsyncCommand()
    drop_indexes = AsyncCommand()
    estimated_document_count = AsyncCommand()
    find_one = AsyncRead()
    find_one_and_delete = AsyncCommand()
    find_one_and_replace = AsyncCommand()
    find_one_and_update = AsyncCommand()
    full_name = ReadOnlyProperty()
    insert_many = AsyncWrite()
    insert_one = AsyncCommand()
    map_reduce = AsyncCommand().wrap(mongomock.Collection)
    name = ReadOnlyProperty()
    reindex = AsyncCommand()
    rename = AsyncCommand()
    replace_one = AsyncCommand()
    update_many = AsyncCommand()
    update_one = AsyncCommand()
    with_options = DelegateMethod().wrap(mongomock.Collection)

    def find(self, *args, **kwargs):
        return AsyncIOMotorCursor(self.delegate.find(*args, **kwargs))
class AgnosticGridOut(AgnosticBase):
    __delegate_class__ = gridfs.GridOut
    __motor_class_name__ = 'MotorGridOut'

    chunk_size = ReadOnlyProperty()
    close = ReadOnlyProperty()
    content_type = ReadOnlyProperty()
    filename = ReadOnlyProperty()
    length = ReadOnlyProperty()
    md5 = ReadOnlyProperty()
    metadata = ReadOnlyProperty()
    name = ReadOnlyProperty()
    read = AsyncRead()
    readable = DelegateMethod()
    readchunk = AsyncRead()
    readline = AsyncRead()
    seek = DelegateMethod()
    seekable = DelegateMethod()
    tell = DelegateMethod()
    upload_date = ReadOnlyProperty()
    write = DelegateMethod()

    def __aiter__(self):
        return self

    async def __anext__(self):
        return next(self.delegate)

    def __getattr__(self, item):
        return getattr(self.delegate, item)
class AgnosticGridIn(AgnosticBase):
    __delegate_class__ = gridfs.GridIn
    __motor_class_name__ = 'MotorGridIn'

    abort = AsyncCommand()
    chunk_size = ReadOnlyProperty()
    closed = ReadOnlyProperty()
    close = AsyncCommand()
    content_type = ReadOnlyProperty()
    filename = ReadOnlyProperty()
    length = ReadOnlyProperty()
    md5 = ReadOnlyProperty()
    name = ReadOnlyProperty()
    read = DelegateMethod()
    readable = DelegateMethod()
    seekable = DelegateMethod()
    upload_date = ReadOnlyProperty()
    write = AsyncCommand().unwrap('MotorGridOut')
    writeable = DelegateMethod()
    writelines = AsyncCommand().unwrap('MotorGridOut')

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.delegate.close()

    def __getattr__(self, item):
        return getattr(self.delegate, item)

    def __setattr__(self, item, value):
        return getattr(self.delegate, item, value)
Beispiel #4
0
class SanicMongoAgnosticClientBase(AgnosticClient):

    max_write_batch_size = ReadOnlyProperty()

    def __getattr__(self, name):
        if name.startswith('_'):
            # the same. Try get from delegate.
            try:
                ret = getattr(self.delegate, name)
            except AttributeError:

                raise AttributeError(
                    "%s has no attribute %r. To access the %s"
                    " database, use client['%s']." %
                    (self.__class__.__name__, name, name, name))
            return ret

        return self[name]

    def __getitem__(self, name):
        db_class = create_class_with_framework(SanicMongoAgnosticDatabase,
                                               self._framework,
                                               self.__module__)

        return db_class(self, name)
class AgnosticCursor(AgnosticCursorBase):
    __delegate_class__ = mongomock.collection.Cursor
    __motor_class_name__ = 'MotorCursor'

    alive = ReadOnlyProperty()
    distinct = AsyncRead()
    limit = MotorCursorChainingMethod()
    skip = MotorCursorChainingMethod()
    sort = MotorCursorChainingMethod()
    hint = MotorCursorChainingMethod()
    max_time_ms = MotorCursorChainingMethod()
Beispiel #6
0
class AgnosticGridOutCursor(AgnosticBaseCursor):
    __motor_class_name__ = 'MotorGridOutCursor'
    __delegate_class__ = gridfs.GridOutCursor

    add_option        = MotorCursorChainingMethod()
    address           = ReadOnlyProperty()
    comment           = MotorCursorChainingMethod()
    count             = AsyncRead()
    distinct          = AsyncRead()
    explain           = AsyncRead()
    hint              = MotorCursorChainingMethod()
    limit             = MotorCursorChainingMethod()
    max               = MotorCursorChainingMethod()
    max_await_time_ms = MotorCursorChainingMethod()
    max_scan          = MotorCursorChainingMethod()
    max_time_ms       = MotorCursorChainingMethod()
    min               = MotorCursorChainingMethod()
    remove_option     = MotorCursorChainingMethod()
    skip              = MotorCursorChainingMethod()
    sort              = MotorCursorChainingMethod()
    where             = MotorCursorChainingMethod()

    # PyMongo's GridOutCursor inherits __die from Cursor.
    _Cursor__die = AsyncCommand()

    def clone(self):
        """Get a clone of this cursor."""
        return self.__class__(self.delegate.clone(), self.collection)

    def next_object(self):
        """Get next GridOut object from cursor."""
        grid_out = super(self.__class__, self).next_object()
        if grid_out:
            grid_out_class = create_class_with_framework(
                AgnosticGridOut, self._framework, self.__module__)

            return grid_out_class(self.collection, delegate=grid_out)
        else:
            # Exhausted.
            return None

    def rewind(self):
        """Rewind this cursor to its unevaluated state."""
        self.delegate.rewind()
        self.started = False
        return self

    def _empty(self):
        return self.delegate._Cursor__empty

    def _query_flags(self):
        return self.delegate._Cursor__query_flags

    def _data(self):
        return self.delegate._Cursor__data

    def _clear_cursor_id(self):
        self.delegate._Cursor__id = 0

    def _close_exhaust_cursor(self):
        # Exhaust MotorGridOutCursors are prohibited.
        pass

    def _killed(self):
        return self.delegate._Cursor__killed

    @motor_coroutine
    def _close(self):
        yield self._framework.yieldable(self._Cursor__die())
Beispiel #7
0
class AgnosticGridIn(object):
    __motor_class_name__ = 'MotorGridIn'
    __delegate_class__ = gridfs.GridIn

    __getattr__  = DelegateMethod()
    abort        = AsyncCommand()
    closed       = ReadOnlyProperty()
    close        = AsyncCommand()
    write        = AsyncCommand().unwrap('MotorGridOut')
    writelines   = AsyncCommand().unwrap('MotorGridOut')
    _id          = ReadOnlyProperty()
    md5          = ReadOnlyProperty()
    filename     = ReadOnlyProperty()
    name         = ReadOnlyProperty()
    content_type = ReadOnlyProperty()
    length       = ReadOnlyProperty()
    chunk_size   = ReadOnlyProperty()
    upload_date  = ReadOnlyProperty()
    set          = AsyncCommand(attr_name='__setattr__', doc="""
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
""")

    def __init__(self, root_collection, delegate=None, **kwargs):
        """
        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`: A :class:`~motor.MotorCollection`, the root
             collection to write to
          - `**kwargs` (optional): file level options (see above)

        .. versionchanged:: 0.2
           ``open`` method removed, no longer needed.
        """
        collection_class = create_class_with_framework(
            AgnosticCollection, self._framework, self.__module__)

        if not isinstance(root_collection, collection_class):
            raise TypeError(
                "First argument to MotorGridIn must be "
                "MotorCollection, not %r" % root_collection)

        self.io_loop = root_collection.get_io_loop()
        if delegate:
            # Short cut.
            self.delegate = delegate
        else:
            self.delegate = self.__delegate_class__(
                root_collection.delegate,
                **kwargs)

    if PY35:
        # Support "async with fs.new_file() as f:"
        exec(textwrap.dedent("""
        async def __aenter__(self):
            return self

        async def __aexit__(self, exc_type, exc_val, exc_tb):
            await self.close()
        """), globals(), locals())

    def get_io_loop(self):
        return self.io_loop