def find(self, *args, **kwargs):
"""Create a :class:`SanicMongoAgnosticCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`SanicMongoAgnosticCursor` without performing any operations
on the server.
``SanicMongoAgnosticCursor`` methods such as
:meth:`~SanicMongoAgnosticCursor.to_list` or
:meth:`~SanicMongoAgnosticCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
cursor_class = create_class_with_framework(
SanicMongoAgnosticCursor, self._framework, self.__module__)
return cursor_class(cursor, self)
python类collection()的实例源码
def find(self, *args, **kwargs):
"""Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``MotorCursor`` methods such as :meth:`~MotorCursor.to_list` or
:meth:`~MotorCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
return MotorCursor(cursor, self)
def __init__(self, database, collection="fs"):
"""
An instance of GridFS on top of a single Database.
:Parameters:
- `database`: a :class:`MotorDatabase`
- `collection` (optional): A string, name of root collection to use,
such as "fs" or "my_files"
.. mongodoc:: gridfs
.. versionchanged:: 0.2
``open`` method removed; no longer needed.
"""
if not isinstance(database, MotorDatabase):
raise TypeError("First argument to MotorGridFS must be "
"MotorDatabase, not %r" % database)
self.io_loop = database.get_io_loop()
self.collection = database[collection]
self.delegate = self.__delegate_class__(
database.delegate,
collection,
_connect=False)
def find(self, *args, **kwargs):
"""Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``MotorCursor`` methods such as :meth:`~MotorCursor.to_list` or
:meth:`~MotorCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
return MotorCursor(cursor, self)
def __init__(self, database, collection="fs"):
"""
An instance of GridFS on top of a single Database.
:Parameters:
- `database`: a :class:`MotorDatabase`
- `collection` (optional): A string, name of root collection to use,
such as "fs" or "my_files"
.. mongodoc:: gridfs
.. versionchanged:: 0.2
``open`` method removed; no longer needed.
"""
if not isinstance(database, MotorDatabase):
raise TypeError("First argument to MotorGridFS must be "
"MotorDatabase, not %r" % database)
self.io_loop = database.get_io_loop()
self.collection = database[collection]
self.delegate = self.__delegate_class__(
database.delegate,
collection,
_connect=False)
def find(self, *args, **kwargs):
"""Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``MotorCursor`` methods such as :meth:`~MotorCursor.to_list` or
:meth:`~MotorCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
return MotorCursor(cursor, self)
def __init__(self, database, collection="fs"):
"""
An instance of GridFS on top of a single Database.
:Parameters:
- `database`: a :class:`MotorDatabase`
- `collection` (optional): A string, name of root collection to use,
such as "fs" or "my_files"
.. mongodoc:: gridfs
.. versionchanged:: 0.2
``open`` method removed; no longer needed.
"""
if not isinstance(database, MotorDatabase):
raise TypeError("First argument to MotorGridFS must be "
"MotorDatabase, not %r" % database)
self.io_loop = database.get_io_loop()
self.collection = database[collection]
self.delegate = self.__delegate_class__(
database.delegate,
collection,
_connect=False)
def find(self, *args, **kwargs):
"""Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``MotorCursor`` methods such as :meth:`~MotorCursor.to_list` or
:meth:`~MotorCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
return MotorCursor(cursor, self)
def __init__(self, database, collection="fs"):
"""
An instance of GridFS on top of a single Database.
:Parameters:
- `database`: a :class:`MotorDatabase`
- `collection` (optional): A string, name of root collection to use,
such as "fs" or "my_files"
.. mongodoc:: gridfs
.. versionchanged:: 0.2
``open`` method removed; no longer needed.
"""
if not isinstance(database, MotorDatabase):
raise TypeError("First argument to MotorGridFS must be "
"MotorDatabase, not %r" % database)
self.io_loop = database.get_io_loop()
self.collection = database[collection]
self.delegate = self.__delegate_class__(
database.delegate,
collection,
_connect=False)
def _increment_atomic_counter(key):
try:
entry = _db.config.find_one_and_update(
{'_id': key},
{
'$setOnInsert': {'_id': key},
'$inc': {'value': 1},
},
upsert=True,
return_document=pymongo.collection.ReturnDocument.AFTER)
except pymongo.errors.DuplicateKeyError:
entry = _db.config.find_one_and_update(
{'_id': key},
{'$inc': {'value': 1}},
return_document=pymongo.collection.ReturnDocument.AFTER)
return entry['value']
def __getstate__(self):
"""
Need for pickling queryset
See https://github.com/MongoEngine/mongoengine/issues/442
"""
obj_dict = self.__dict__.copy()
# don't picke collection, instead pickle collection params
obj_dict.pop('_collection_obj')
# don't pickle cursor
obj_dict['_cursor_obj'] = None
return obj_dict
def find(self, *args, **kwargs):
"""Create a :class:`MongoMotorAgnosticCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not take a `callback` parameter, nor does
it return a Future, because ``find`` merely creates a
:class:`MongoMotorAgnosticCursor` without performing any operations
on the server.
``MongoMotorAgnosticCursor`` methods such as
:meth:`~MongoMotorAgnosticCursor.to_list` or
:meth:`~MongoMotorAgnosticCursor.count` perform actual operations.
"""
if 'callback' in kwargs:
raise pymongo.errors.InvalidOperation(
"Pass a callback to each, to_list, or count, not to find.")
cursor = self.delegate.find(*args, **kwargs)
cursor_class = create_class_with_framework(
MongoMotorAgnosticCursor, self._framework, self.__module__)
return cursor_class(cursor, self)
def __getitem__(self, index):
r = self.delegate[index]
if isinstance(r, type(self.delegate)):
# If the response is a cursor, transform it into a
# SanicMongo cursor.
r = type(self)(r, self.collection)
return r
def __getattr__(self, name):
if name.startswith('_'):
# Here first I try to get the _attribute from
# from the delegate obj.
try:
ret = getattr(self.delegate, name)
except AttributeError:
raise AttributeError(
"%s has no attribute %r. To access the %s"
" collection, use collection['%s']." % (
self.__class__.__name__, name, name,
name))
return ret
return self[name]
def __getattr__(self, name):
if name.startswith('_'):
# samething. try get from delegate first
try:
ret = getattr(self.delegate, name)
except AttributeError:
raise AttributeError(
"%s has no attribute %r. To access the %s"
" collection, use database['%s']." % (
self.__class__.__name__, name, name,
name))
return ret
return self[name]
def wrap(self, collection):
# Replace pymongo.collection.Collection with MotorCollection
return self[collection.name]
def __getattr__(self, name):
# Dotted collection name, like "foo.bar".
return MotorCollection(self.database, self.name + '.' + name)
def parallel_scan(self, num_cursors, **kwargs):
"""Scan this entire collection in parallel.
Returns a list of up to ``num_cursors`` cursors that can be iterated
concurrently. As long as the collection is not modified during
scanning, each document appears once in one of the cursors' result
sets.
For example, to process each document in a collection using some
function ``process_document()``::
@gen.coroutine
def process_cursor(cursor):
while (yield cursor.fetch_next):
process_document(document)
# Get up to 4 cursors.
cursors = yield collection.parallel_scan(4)
yield [process_cursor(cursor) for cursor in cursors]
# All documents have now been processed.
If ``process_document()`` is a coroutine, do
``yield process_document(document)``.
With :class:`MotorReplicaSetClient`, pass `read_preference` of
:attr:`~pymongo.read_preference.ReadPreference.SECONDARY_PREFERRED`
to scan a secondary.
:Parameters:
- `num_cursors`: the number of cursors to return
.. note:: Requires server version **>= 2.5.5**.
"""
command_cursors = yield self.__parallel_scan(num_cursors, **kwargs)
motor_command_cursors = [
MotorCommandCursor(cursor, self)
for cursor in command_cursors]
raise gen.Return(motor_command_cursors)
def wrap(self, obj):
if obj.__class__ is Collection:
# Replace pymongo.collection.Collection with MotorCollection
return self.database[obj.name]
elif obj.__class__ is Cursor:
return MotorCursor(obj, self)
elif obj.__class__ is CommandCursor:
return MotorCommandCursor(obj, self)
else:
return obj
def get_io_loop(self):
return self.collection.get_io_loop()
def clone(self):
"""Get a clone of this cursor."""
return MotorCursor(self.delegate.clone(), self.collection)
def __copy__(self):
return MotorCursor(self.delegate.__copy__(), self.collection)
def next_object(self):
"""Get next GridOut object from cursor."""
grid_out = super(MotorGridOutCursor, self).next_object()
if grid_out:
return MotorGridOut(self.collection, delegate=grid_out)
else:
# Exhausted.
return None
def __init__(self, collection, ordered):
self.io_loop = collection.get_io_loop()
delegate = BulkOperationBuilder(collection.delegate, ordered)
super(MotorBulkOperationBuilder, self).__init__(delegate)
def wrap(self, collection):
# Replace pymongo.collection.Collection with MotorCollection
return self[collection.name]
def __getattr__(self, name):
# Dotted collection name, like "foo.bar".
return MotorCollection(self.database, self.name + '.' + name)
def parallel_scan(self, num_cursors, **kwargs):
"""Scan this entire collection in parallel.
Returns a list of up to ``num_cursors`` cursors that can be iterated
concurrently. As long as the collection is not modified during
scanning, each document appears once in one of the cursors' result
sets.
For example, to process each document in a collection using some
function ``process_document()``::
@gen.coroutine
def process_cursor(cursor):
while (yield cursor.fetch_next):
process_document(document)
# Get up to 4 cursors.
cursors = yield collection.parallel_scan(4)
yield [process_cursor(cursor) for cursor in cursors]
# All documents have now been processed.
If ``process_document()`` is a coroutine, do
``yield process_document(document)``.
With :class:`MotorReplicaSetClient`, pass `read_preference` of
:attr:`~pymongo.read_preference.ReadPreference.SECONDARY_PREFERRED`
to scan a secondary.
:Parameters:
- `num_cursors`: the number of cursors to return
.. note:: Requires server version **>= 2.5.5**.
"""
command_cursors = yield self.__parallel_scan(num_cursors, **kwargs)
motor_command_cursors = [
MotorCommandCursor(cursor, self)
for cursor in command_cursors]
raise gen.Return(motor_command_cursors)
def wrap(self, obj):
if obj.__class__ is Collection:
# Replace pymongo.collection.Collection with MotorCollection
return self.database[obj.name]
elif obj.__class__ is Cursor:
return MotorCursor(obj, self)
elif obj.__class__ is CommandCursor:
return MotorCommandCursor(obj, self)
else:
return obj
def get_io_loop(self):
return self.collection.get_io_loop()
def clone(self):
"""Get a clone of this cursor."""
return MotorCursor(self.delegate.clone(), self.collection)