本文整理汇总了Python中mongoengine.base.get_document函数的典型用法代码示例。如果您正苦于以下问题:Python get_document函数的具体用法?Python get_document怎么用?Python get_document使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_document函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find_references
def _find_references(self, items, depth=0):
"""
Recursively finds all db references to be dereferenced
:param items: The iterable (dict, list, queryset)
:param depth: The current depth of recursion
"""
reference_map = {}
if not items or depth >= self.max_depth:
return reference_map
# Determine the iterator to use
if isinstance(items, dict):
iterator = items.values()
else:
iterator = items
# Recursively find dbreferences
depth += 1
for item in iterator:
if isinstance(item, (Document, EmbeddedDocument)):
for field_name, field in item._fields.iteritems():
v = item._data.get(field_name, None)
if isinstance(v, LazyReference):
# LazyReference inherits DBRef but should not be dereferenced here !
continue
elif isinstance(v, DBRef):
reference_map.setdefault(field.document_type, set()).add(v.id)
elif isinstance(v, (dict, SON)) and '_ref' in v:
reference_map.setdefault(get_document(v['_cls']), set()).add(v['_ref'].id)
elif isinstance(v, (dict, list, tuple)) and depth <= self.max_depth:
field_cls = getattr(getattr(field, 'field', None), 'document_type', None)
references = self._find_references(v, depth)
for key, refs in references.iteritems():
if isinstance(field_cls, (Document, TopLevelDocumentMetaclass)):
key = field_cls
reference_map.setdefault(key, set()).update(refs)
elif isinstance(item, LazyReference):
# LazyReference inherits DBRef but should not be dereferenced here !
continue
elif isinstance(item, DBRef):
reference_map.setdefault(item.collection, set()).add(item.id)
elif isinstance(item, (dict, SON)) and '_ref' in item:
reference_map.setdefault(get_document(item['_cls']), set()).add(item['_ref'].id)
elif isinstance(item, (dict, list, tuple)) and depth - 1 <= self.max_depth:
references = self._find_references(item, depth - 1)
for key, refs in references.iteritems():
reference_map.setdefault(key, set()).update(refs)
return reference_map
示例2: _get_document
def _get_document(self, tag):
try:
doc = get_document(tag)
except NotRegistered:
pass
else:
return doc
示例3: register_delete_rule
def register_delete_rule(cls, document_cls, field_name, rule):
"""This method registers the delete rules to apply when removing this
object.
"""
classes = [get_document(class_name)
for class_name in cls._subclasses
if class_name != cls.__name__] + [cls]
documents = [get_document(class_name)
for class_name in document_cls._subclasses
if class_name != document_cls.__name__] + [document_cls]
for klass in classes:
for document_cls in documents:
delete_rules = klass._meta.get('delete_rules') or {}
delete_rules[(document_cls, field_name)] = rule
klass._meta['delete_rules'] = delete_rules
示例4: document_types
def document_types(self):
for idx, document_type in enumerate(self.document_types_obj):
if isinstance(document_type, basestring):
if document_type == RECURSIVE_REFERENCE_CONSTANT:
self.document_types_obj[idx] = self.owner_document
else:
self.document_types_obj[idx] = get_document(document_type)
return self.document_types_obj
示例5: __init__
def __init__(self, model, view, form_class, form_opts=None, **kwargs):
super(ModelFormField, self).__init__(form_class, **kwargs)
self.model = model
if isinstance(self.model, str):
self.model = get_document(self.model)
self.view = view
self.form_opts = form_opts
示例6: document_types
def document_types(self):
"""Lazy property, used on-demand in particular cases"""
if not self.document_types_obj:
for document_type in self.document_types_str:
if document_type == RECURSIVE_REFERENCE_CONSTANT:
self.document_types_obj.append(self.owner_document)
else:
self.document_types_obj.append(get_document(document_type))
return self.document_types_obj
示例7: _fetch_objects
def _fetch_objects(self, doc_type=None):
"""Fetch all references and convert to their document objects
"""
object_map = {}
for collection, dbrefs in iteritems(self.reference_map):
# we use getattr instead of hasattr because hasattr swallows any exception under python2
# so it could hide nasty things without raising exceptions (cfr bug #1688))
ref_document_cls_exists = (getattr(collection, 'objects', None) is not None)
if ref_document_cls_exists:
col_name = collection._get_collection_name()
refs = [dbref for dbref in dbrefs
if (col_name, dbref) not in object_map]
references = collection.objects.in_bulk(refs)
for key, doc in iteritems(references):
object_map[(col_name, key)] = doc
else: # Generic reference: use the refs data to convert to document
if isinstance(doc_type, (ListField, DictField, MapField)):
continue
refs = [dbref for dbref in dbrefs
if (collection, dbref) not in object_map]
if doc_type:
references = doc_type._get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
doc = doc_type._from_son(ref)
object_map[(collection, doc.id)] = doc
else:
references = get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
if '_cls' in ref:
doc = get_document(ref['_cls'])._from_son(ref)
elif doc_type is None:
doc = get_document(
''.join(x.capitalize()
for x in collection.split('_')))._from_son(ref)
else:
doc = doc_type._from_son(ref)
object_map[(collection, doc.id)] = doc
return object_map
示例8: klass
def klass(class_object_or_name):
if inspect.isclass(class_object_or_name):
return class_object_or_name
if not isinstance(class_object_or_name, basestring):
raise TypeError("'%s' must be either a class or a string." % class_object_or_name)
try:
return get_document(class_object_or_name)
except KeyError:
raise NameError("name '%s' is not defined." % class_object_or_name)
示例9: to_internal_value
def to_internal_value(self, data):
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
try:
doc_name = data['_cls']
doc_cls = get_document(doc_name)
except KeyError:
self.fail('missing_class')
except NotRegistered:
self.fail('undefined_model', doc_cls=doc_name)
return doc_cls(**data)
示例10: _fetch_objects
def _fetch_objects(self, doc_type=None):
"""Fetch all references and convert to their document objects
"""
object_map = {}
for collection, dbrefs in self.reference_map.iteritems():
if hasattr(collection, 'objects'): # We have a document class for the refs
col_name = collection._get_collection_name()
refs = [dbref for dbref in dbrefs
if (col_name, dbref) not in object_map]
references = collection.objects.in_bulk(refs)
for key, doc in references.iteritems():
object_map[(col_name, key)] = doc
else: # Generic reference: use the refs data to convert to document
if isinstance(doc_type, (ListField, DictField, MapField,)):
continue
refs = [dbref for dbref in dbrefs
if (collection, dbref) not in object_map]
if doc_type:
references = doc_type._get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
doc = doc_type._from_son(ref)
object_map[(collection, doc.id)] = doc
else:
references = get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
if '_cls' in ref:
doc = get_document(ref['_cls'])._from_son(ref)
elif doc_type is None:
doc = get_document(
''.join(x.capitalize()
for x in collection.split('_')))._from_son(ref)
else:
doc = doc_type._from_son(ref)
object_map[(collection, doc.id)] = doc
return object_map
示例11: test_core_access
def test_core_access(self, app):
"""Tests that core functions can be accessed"""
with app.test_request_context('/'):
# check core URLs
v1_user = url_for('v1.user')
v1_user_path = url_for('v1.user_path', path='user')
assert v1_user is not None
assert v1_user_path is not None
# check core models
user = get_document('User')
assert user is not None
assert hasattr(user, 'objects')
示例12: test_template_access
def test_template_access(self, app):
"""tests that template functions can be accessed"""
with app.test_request_context('/'):
# check template URLs
v1_sample = url_for('v1.sample')
v1_sample_path = url_for('v1.sample_path', path='sample')
assert v1_sample is not None
assert v1_sample_path is not None
# check template models
sample = get_document('Sample')
assert sample is not None
assert hasattr(sample, 'objects')
示例13: _deserialize
def _deserialize(self, value, attr, data):
# To deserialize a generic reference, we need a _cls field in addition
# with the id field
if not isinstance(value, dict) or not value.get('id') or not value.get('_cls'):
raise ValidationError("Need a dict with 'id' and '_cls' fields")
doc_id = value['id']
doc_cls_name = value['_cls']
if self.document_class_choices and doc_cls_name not in self.document_class_choices:
raise ValidationError("Invalid _cls field `%s`, must be one of %s" %
(doc_cls_name, self.document_class_choices))
try:
doc_cls = get_document(doc_cls_name)
except NotRegistered:
raise ValidationError("Invalid _cls field `%s`" % doc_cls_name)
try:
doc = doc_cls.objects.get(pk=doc_id)
except (doc_cls.DoesNotExist, MongoValidationError, ValueError, TypeError):
raise ValidationError('unknown document %s `%s`' %
(doc_cls_name, value))
return doc
示例14: resolve_model
def resolve_model(self, model):
'''
Resolve a model given a name or dict with `class` entry.
:raises ValueError: model specification is wrong or does not exists
'''
if not model:
raise ValueError('Unsupported model specifications')
if isinstance(model, basestring):
classname = model
elif isinstance(model, dict) and 'class' in model:
classname = model['class']
else:
raise ValueError('Unsupported model specifications')
try:
return get_document(classname)
except self.NotRegistered:
message = 'Model "{0}" does not exist'.format(classname)
raise ValueError(message)
示例15: to_internal_value
def to_internal_value(self, value):
if not isinstance(value, dict):
self.fail("not_a_dict", input_type=type(value).__name__)
try:
doc_name = value["_cls"]
doc_id = value["_id"]
except KeyError:
self.fail("missing_items")
try:
doc_cls = get_document(doc_name)
except NotRegistered:
self.fail("undefined_model", doc_cls=doc_name)
try:
doc_id = self.pk_field.to_internal_value(doc_id)
except:
self.fail("invalid_id", pk_value=repr(doc_id), pk_type=self.pk_field_class.__name__)
try:
return doc_cls.objects.only("id").get(id=doc_id)
except DoesNotExist:
self.fail("not_found", pk_value=doc_id)