我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用google.appengine.ext.db.Model()。
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes since ndb and db models are # new-style if isinstance(self._model, type): if ndb is not None and issubclass(self._model, ndb.Model): return True elif issubclass(self._model, db.Model): return False raise TypeError('Model class not an NDB or DB model: %s.' % (self._model,))
def transform_xdb_stubs(payload, context): """ Called when a successful decode has been performed. Transform the stubs within the payload to proper db.Model instances. """ stubs = context.get(XDB_STUB_NAME, None) if not stubs: return payload stubs.transform() return payload # initialise the module here: hook into pyamf
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes since ndb and db models are # new-style if isinstance(self._model, type): if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL): return True elif issubclass(self._model, db.Model): return False raise TypeError( 'Model class not an NDB or DB model: {0}.'.format(self._model))
def from_entity(cls, entity): """Load from entity to class based on discriminator. Rather than instantiating a new Model instance based on the kind mapping, this creates an instance of the correct model class based on the entities class-key. Args: entity: Entity loaded directly from datastore. Raises: KindError when there is no class mapping based on discriminator. """ if (_CLASS_KEY_PROPERTY in entity and tuple(entity[_CLASS_KEY_PROPERTY]) != cls.class_key()): key = tuple(entity[_CLASS_KEY_PROPERTY]) try: poly_class = _class_map[key] except KeyError: raise db.KindError('No implementation for class \'%s\'' % (key,)) return poly_class.from_entity(entity) return super(PolyModel, cls).from_entity(entity)
def __init__(self, query_string, model_class, *args, **kwds): """Constructor. Args: query_string: Properly formatted GQL query string. model_class: Model class from which entities are constructed. *args: Positional arguments used to bind numeric references in the query. **kwds: Dictionary-based arguments for named references. """ from google.appengine.ext import gql app = kwds.pop('_app', None) self._proto_query = gql.GQL(query_string, _app=app, namespace='') super(db.GqlQuery, self).__init__(model_class) self.bind(*args, **kwds)
def make_directed_query(self, kind_class, keys_only=False): """Construct a query for this key range, including the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, use keys_only on Query? Returns: A db.Query or ndb.Query instance (corresponding to kind_class). Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_directed_ndb_query(kind_class, keys_only=keys_only) assert self._app is None, '_app is not supported for db.Query' direction = self.__get_direction("", "-") query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("%s__key__" % direction) query = self.filter_query(query) return query
def make_ascending_ndb_query(self, kind_class, keys_only=False, filters=None): """Construct an NDB query for this key range, without the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, query only for keys. Returns: An ndb.Query instance. """ assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query, filters=filters) query = query.order(kind_class._key) return query
def GetImplementationClass(kind_or_class_key): """Returns the implementation class for a given kind or class key. Args: kind_or_class_key: A kind string or a tuple of kind strings. Return: A db.Model subclass for the given kind or class key. """ if isinstance(kind_or_class_key, tuple): try: implementation_class = polymodel._class_map[kind_or_class_key] except KeyError: raise db.KindError('No implementation for class \'%s\'' % kind_or_class_key) else: implementation_class = db.class_for_kind(kind_or_class_key) return implementation_class
def handle_entity(self, entity): """Subclasses can override this to add custom entity conversion code. This is called for each entity, after its properties are populated from the input but before it is stored. Subclasses can override this to add custom entity handling code. The entity to be inserted should be returned. If multiple entities should be inserted, return a list of entities. If no entities should be inserted, return None or []. Args: entity: db.Model Returns: db.Model or list of db.Model """ return entity
def __init__(self, model, key_name, property_name, cache=None, user=None): """Constructor for Storage. Args: model: db.Model or ndb.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty or CredentialsNDBProperty. cache: memcache, a write-through cache to put in front of the datastore. If the model you are using is an NDB model, using a cache will be redundant since the model uses an instance cache and memcache for you. user: users.User object, optional. Can be used to grab user ID as a key_name if no key name is specified. """ if key_name is None: if user is None: raise ValueError('StorageByKeyName called with no key name or user.') key_name = user.user_id() self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache
def __init__(self, model, key_name, property_name, cache=None, user=None): """Constructor for Storage. Args: model: db.Model or ndb.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty or CredentialsNDBProperty. cache: memcache, a write-through cache to put in front of the datastore. If the model you are using is an NDB model, using a cache will be redundant since the model uses an instance cache and memcache for you. user: users.User object, optional. Can be used to grab user ID as a key_name if no key name is specified. """ if key_name is None: if user is None: raise ValueError('StorageByKeyName called with no ' 'key name or user.') key_name = user.user_id() self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes since ndb and db models are # new-style if isinstance(self._model, type): if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL): return True elif issubclass(self._model, db.Model): return False raise TypeError('Model class not an NDB or DB model: %s.' % (self._model,))
def key_for_entity(cls, entity_or_key): """Return the metadata key for the entity group containing entity_or_key. Use this key to get() the __entity_group__ metadata entity for the entity group containing entity_or_key. Args: entity_or_key: a key or entity whose __entity_group__ key you want. Returns: The __entity_group__ key for the entity group containing entity_or_key. """ if isinstance(entity_or_key, db.Model): key = entity_or_key.key() else: key = entity_or_key while key.parent(): key = key.parent() return db.Key.from_path(cls.KIND_NAME, cls.ID, parent=key)
def make_ascending_query(self, kind_class, keys_only=False, filters=None): """Construct a query for this key range without setting the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, query only for keys. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: A db.Query or ndb.Query instance (corresponding to kind_class). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_ascending_ndb_query( kind_class, keys_only=keys_only, filters=filters) assert self._app is None, '_app is not supported for db.Query' query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("__key__") query = self.filter_query(query, filters=filters) return query
def validate(cls, mapper_spec): """Inherit docs.""" super(DatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] try: model_class = util.for_name(entity_kind) except ImportError, e: raise BadReaderParamsError("Bad entity kind: %s" % e) if cls.FILTERS_PARAM in params: filters = params[cls.FILTERS_PARAM] if issubclass(model_class, db.Model): cls._validate_filters(filters, model_class) else: cls._validate_filters_ndb(filters, model_class) property_range.PropertyRange(filters, entity_kind)
def _validate_filters_ndb(cls, filters, model_class): """Validate ndb.Model filters.""" if not filters: return properties = model_class._properties for f in filters: prop, _, val = f if prop not in properties: raise errors.BadReaderParamsError( "Property %s is not defined for entity type %s", prop, model_class._get_kind()) try: properties[prop]._do_validate(val) except db.BadValueError, e: raise errors.BadReaderParamsError(e)
def validate(cls, job_config): """Inherit docs.""" super(ModelDatastoreInputReader, cls).validate(job_config) params = job_config.input_reader_params entity_kind = params[cls.ENTITY_KIND_PARAM] try: model_class = util.for_name(entity_kind) except ImportError, e: raise errors.BadReaderParamsError("Bad entity kind: %s" % e) if cls.FILTERS_PARAM in params: filters = params[cls.FILTERS_PARAM] if issubclass(model_class, db.Model): cls._validate_filters(filters, model_class) else: cls._validate_filters_ndb(filters, model_class) property_range.PropertyRange(filters, entity_kind)