text stringlengths 81 112k |
|---|
Parse a BlobInfo record from file upload field_storage.
Args:
field_storage: cgi.FieldStorage that represents uploaded blob.
Returns:
BlobInfo record as parsed from the field-storage instance.
None if there was no field_storage.
Raises:
BlobInfoParseError when provided field_storage does not co... |
Fetch data for blob.
Fetches a fragment of a blob up to MAX_BLOB_FETCH_SIZE in length. Attempting
to fetch a fragment that extends beyond the boundaries of the blob will return
the amount of data from start_index until the end of the blob, which will be
a smaller size than requested. Requesting a fragment wh... |
Async version of fetch_data().
def fetch_data_async(blob, start_index, end_index, **options):
"""Async version of fetch_data()."""
if isinstance(blob, BlobInfo):
blob = blob.key()
rpc = blobstore.create_rpc(**options)
rpc = blobstore.fetch_data_async(blob, start_index, end_index, rpc=rpc)
result = yield ... |
Retrieve a BlobInfo by key.
Args:
blob_key: A blob key. This may be a str, unicode or BlobKey instance.
**ctx_options: Context options for Model().get_by_id().
Returns:
A BlobInfo entity associated with the provided key, If there was
no such entity, returns None.
def get(cls, blob_k... |
Async version of get().
def get_async(cls, blob_key, **ctx_options):
"""Async version of get()."""
if not isinstance(blob_key, (BlobKey, basestring)):
raise TypeError('Expected blob key, got %r' % (blob_key,))
if 'parent' in ctx_options:
raise TypeError('Parent is not supported')
return cls... |
Multi-key version of get().
Args:
blob_keys: A list of blob keys.
**ctx_options: Context options for Model().get_by_id().
Returns:
A list whose items are each either a BlobInfo entity or None.
def get_multi(cls, blob_keys, **ctx_options):
"""Multi-key version of get().
Args:
... |
Async version of get_multi().
def get_multi_async(cls, blob_keys, **ctx_options):
"""Async version of get_multi()."""
for blob_key in blob_keys:
if not isinstance(blob_key, (BlobKey, basestring)):
raise TypeError('Expected blob key, got %r' % (blob_key,))
if 'parent' in ctx_options:
rai... |
Permanently delete this blob from Blobstore.
Args:
**options: Options for create_rpc().
def delete(self, **options):
"""Permanently delete this blob from Blobstore.
Args:
**options: Options for create_rpc().
"""
fut = delete_async(self.key(), **options)
fut.get_result() |
Fills the internal buffer.
Args:
size: Number of bytes to read. Will be clamped to
[self.__buffer_size, MAX_BLOB_FETCH_SIZE].
def __fill_buffer(self, size=0):
"""Fills the internal buffer.
Args:
size: Number of bytes to read. Will be clamped to
[self.__buffer_size, MAX_BLOB_FE... |
Returns the BlobInfo for this file.
def blob_info(self):
"""Returns the BlobInfo for this file."""
if not self.__blob_info:
self.__blob_info = BlobInfo.get(self.__blob_key)
return self.__blob_info |
Create a new Connection object with the right adapter.
Optionally you can pass in a datastore_rpc.Configuration object.
def make_connection(config=None, default_model=None,
_api_version=datastore_rpc._DATASTORE_V3,
_id_resolver=None):
"""Create a new Connection object with ... |
Internal helper to unpack a User value from a protocol buffer.
def _unpack_user(v):
"""Internal helper to unpack a User value from a protocol buffer."""
uv = v.uservalue()
email = unicode(uv.email().decode('utf-8'))
auth_domain = unicode(uv.auth_domain().decode('utf-8'))
obfuscated_gaiaid = uv.obfuscated_gai... |
Convert a date to a datetime for Cloud Datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00.
def _date_to_datetime(value):
"""Convert a date to a datetime for Cloud Datastore storage.
Args:
value: A datetime.date object.
Returns:
A datet... |
Convert a time to a datetime for Cloud Datastore storage.
Args:
value: A datetime.time object.
Returns:
A datetime object with date set to 1970-01-01.
def _time_to_datetime(value):
"""Convert a time to a datetime for Cloud Datastore storage.
Args:
value: A datetime.time object.
Returns:
A... |
Decorator to make a function automatically run in a transaction.
Args:
**ctx_options: Transaction options (see transaction(), but propagation
default to TransactionOptions.ALLOWED).
This supports two forms:
(1) Vanilla:
@transactional
def callback(arg):
...
(2) With options:
... |
The async version of @ndb.transaction.
def transactional_async(func, args, kwds, **options):
"""The async version of @ndb.transaction."""
options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED)
if args or kwds:
return transaction_async(lambda: func(*args, **kwds), **options)
return tran... |
The async version of @ndb.transaction.
Will return the result of the wrapped function as a Future.
def transactional_tasklet(func, args, kwds, **options):
"""The async version of @ndb.transaction.
Will return the result of the wrapped function as a Future.
"""
from . import tasklets
func = tasklets.taskl... |
A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exception if called from within
a transaction. If true, temporar... |
Updates all descendants to a specified value.
def _set(self, value):
"""Updates all descendants to a specified value."""
if self.__is_parent_node():
for child in self.__sub_counters.itervalues():
child._set(value)
else:
self.__counter = value |
Internal helper for comparison operators.
Args:
op: The operator ('=', '<' etc.).
Returns:
A FilterNode instance representing the requested comparison.
def _comparison(self, op, value):
"""Internal helper for comparison operators.
Args:
op: The operator ('=', '<' etc.).
Return... |
Comparison operator for the 'in' comparison operator.
The Python 'in' operator cannot be overloaded in the way we want
to, so we define a method. For example::
Employee.query(Employee.rank.IN([4, 5, 6]))
Note that the method is called ._IN() but may normally be invoked
as .IN(); ._IN() is prov... |
Call all validations on the value.
This calls the most derived _validate() method(s), then the custom
validator function, and then checks the choices. It returns the
value, possibly modified in an idempotent way, or raises an
exception.
Note that this does not call all composable _validate() meth... |
Internal helper called to tell the property its name.
This is called by _fix_up_properties() which is called by
MetaModel when finishing the construction of a Model subclass.
The name passed in is the name of the class attribute to which the
Property is assigned (a.k.a. the code name). Note that this ... |
Internal helper to set a value in an entity for a Property.
This performs validation first. For a repeated Property the value
should be a list.
def _set_value(self, entity, value):
"""Internal helper to set a value in an entity for a Property.
This performs validation first. For a repeated Property... |
Internal helper to retrieve the value for this Property from an entity.
This returns None if no value is set, or the default argument if
given. For a repeated Property this returns a list if a value is
set, otherwise None. No additional transformations are applied.
def _retrieve_value(self, entity, defa... |
Like _get_base_value(), but always returns a list.
Returns:
A new list of unwrapped base values. For an unrepeated
property, if the value is missing or None, returns [None]; for a
repeated property, if the original value is missing or None or
empty, returns [].
def _get_base_value_unwrapp... |
Call _from_base_type() if necessary.
If the value is a _BaseValue instance, unwrap it and call all
_from_base_type() methods. Otherwise, return the value
unchanged.
def _opt_call_from_base_type(self, value):
"""Call _from_base_type() if necessary.
If the value is a _BaseValue instance, unwrap it... |
Call _to_base_type() if necessary.
If the value is a _BaseValue instance, return it unchanged.
Otherwise, call all _validate() and _to_base_type() methods and
wrap it in a _BaseValue instance.
def _opt_call_to_base_type(self, value):
"""Call _to_base_type() if necessary.
If the value is a _BaseVa... |
Call all _from_base_type() methods on the value.
This calls the methods in the reverse method resolution order of
the property's class.
def _call_from_base_type(self, value):
"""Call all _from_base_type() methods on the value.
This calls the methods in the reverse method resolution order of
the p... |
Call all _validate() and _to_base_type() methods on the value.
This calls the methods in the method resolution order of the
property's class.
def _call_to_base_type(self, value):
"""Call all _validate() and _to_base_type() methods on the value.
This calls the methods in the method resolution order of... |
Call the initial set of _validate() methods.
This is similar to _call_to_base_type() except it only calls
those _validate() methods that can be called without needing to
call _to_base_type().
An example: suppose the class hierarchy is A -> B -> C ->
Property, and suppose A defines _validate() only... |
Compute a list of composable methods.
Because this is a common operation and the class hierarchy is
static, the outcome is cached (assuming that for a particular list
of names the reversed flag is either always on, or always off).
Args:
*names: One or more method names.
reverse: Optional f... |
Return a single callable that applies a list of methods to a value.
If a method returns None, the last value is kept; if it returns
some other value, that replaces the last value. Exceptions are
not caught.
def _apply_list(self, methods):
"""Return a single callable that applies a list of methods to ... |
Apply a function to the property value/values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each of the values in the list. The
resulting value or list of values is both stored... |
Internal helper to get the value for this Property from an entity.
For a repeated Property this initializes the value to an empty
list if it is not set.
def _get_value(self, entity):
"""Internal helper to get the value for this Property from an entity.
For a repeated Property this initializes the val... |
Internal helper to delete the value for this Property from an entity.
Note that if no value exists this is a no-op; deleted values will
not be serialized but requesting their value will return None (or
an empty list in the case of a repeated Property).
def _delete_value(self, entity):
"""Internal help... |
Internal helper to ask if the entity has a value for this Property.
This returns False if a value is stored but it is None.
def _is_initialized(self, entity):
"""Internal helper to ask if the entity has a value for this Property.
This returns False if a value is stored but it is None.
"""
return ... |
Internal helper to serialize this property to a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
pb: The protocol buffer, an EntityProto instance.
prefix: Optional name prefix used for StructuredProperty
(if present, must en... |
Internal helper to deserialize this property from a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
p: A Property Message object (a protocol buffer).
depth: Optional nesting depth, default 1 (unused here, but used
by some s... |
Internal helper to check this property for specific requirements.
Called by Model._check_properties().
Args:
rest: Optional subproperty to check, of the form 'name1.name2...nameN'.
Raises:
InvalidPropertyError if this property does not meet the given
requirements or if a subproperty is ... |
Setter for key attribute.
def _set_value(self, entity, value):
"""Setter for key attribute."""
if value is not None:
value = _validate_key(value, entity=entity)
value = entity._validate_key(value)
entity._entity_key = value |
Override _get_value() to *not* raise UnprojectedPropertyError.
def _get_value(self, entity):
"""Override _get_value() to *not* raise UnprojectedPropertyError."""
value = self._get_user_value(entity)
if value is None and entity._projection:
# Invoke super _get_value() to raise the proper exception.
... |
Override for Property._check_property().
Raises:
InvalidPropertyError if no subproperty is specified or if something
is wrong with the subproperty.
def _check_property(self, rest=None, require_indexed=True):
"""Override for Property._check_property().
Raises:
InvalidPropertyError if no ... |
Internal helper method to parse keywords that may be property names.
def __get_arg(cls, kwds, kwd):
"""Internal helper method to parse keywords that may be property names."""
alt_kwd = '_' + kwd
if alt_kwd in kwds:
return kwds.pop(alt_kwd)
if kwd in kwds:
obj = getattr(cls, kwd, None)
... |
Internal helper to set attributes from keyword arguments.
Expando overrides this.
def _set_attributes(self, kwds):
"""Internal helper to set attributes from keyword arguments.
Expando overrides this.
"""
cls = self.__class__
for name, value in kwds.iteritems():
prop = getattr(cls, name)... |
Internal helper to find uninitialized properties.
Returns:
A set of property names.
def _find_uninitialized(self):
"""Internal helper to find uninitialized properties.
Returns:
A set of property names.
"""
return set(name
for name, prop in self._properties.iteritems()
... |
Internal helper to check for uninitialized properties.
Raises:
BadValueError if it finds any.
def _check_initialized(self):
"""Internal helper to check for uninitialized properties.
Raises:
BadValueError if it finds any.
"""
baddies = self._find_uninitialized()
if baddies:
r... |
Clear the kind map. Useful for testing.
def _reset_kind_map(cls):
"""Clear the kind map. Useful for testing."""
# Preserve "system" kinds, like __namespace__
keep = {}
for name, value in cls._kind_map.iteritems():
if name.startswith('__') and name.endswith('__'):
keep[name] = value
... |
Get the model class for the kind.
Args:
kind: A string representing the name of the kind to lookup.
default_model: The model class to use if the kind can't be found.
Returns:
The model class for the requested kind.
Raises:
KindError: The kind was not found and no default_model was ... |
Compare two entities of the same class, excluding keys.
def _equivalent(self, other):
"""Compare two entities of the same class, excluding keys."""
if other.__class__ is not self.__class__: # TODO: What about subclasses?
raise NotImplementedError('Cannot compare different model classes. '
... |
Internal helper to turn an entity into an EntityProto protobuf.
def _to_pb(self, pb=None, allow_partial=False, set_key=True):
"""Internal helper to turn an entity into an EntityProto protobuf."""
if not allow_partial:
self._check_initialized()
if pb is None:
pb = entity_pb.EntityProto()
if... |
Internal helper to copy the key into a protobuf.
def _key_to_pb(self, pb):
"""Internal helper to copy the key into a protobuf."""
key = self._key
if key is None:
pairs = [(self._get_kind(), None)]
ref = key_module._ReferenceFromPairs(pairs, reference=pb.mutable_key())
else:
ref = key.... |
Internal helper to create an entity from an EntityProto protobuf.
def _from_pb(cls, pb, set_key=True, ent=None, key=None):
"""Internal helper to create an entity from an EntityProto protobuf."""
if not isinstance(pb, entity_pb.EntityProto):
raise TypeError('pb must be a EntityProto; received %r' % pb)
... |
Internal helper to get the Property for a protobuf-level property.
def _get_property_for(self, p, indexed=True, depth=0):
"""Internal helper to get the Property for a protobuf-level property."""
parts = p.name().split('.')
if len(parts) <= depth:
# Apparently there's an unstructured value here.
... |
Internal helper to clone self._properties if necessary.
def _clone_properties(self):
"""Internal helper to clone self._properties if necessary."""
cls = self.__class__
if self._properties is cls._properties:
self._properties = dict(cls._properties) |
Internal helper to create a fake Property.
def _fake_property(self, p, next, indexed=True):
"""Internal helper to create a fake Property."""
self._clone_properties()
if p.name() != next and not p.name().endswith('.' + next):
prop = StructuredProperty(Expando, next)
prop._store_value(self, _Base... |
Return a dict containing the entity's property values.
Args:
include: Optional set of property names to include, default all.
exclude: Optional set of property names to skip, default none.
A name contained in both include and exclude is excluded.
def _to_dict(self, include=None, exclude=None):... |
Fix up the properties by calling their _fix_up() method.
Note: This is called by MetaModel, but may also be called manually
after dynamically updating a model class.
def _fix_up_properties(cls):
"""Fix up the properties by calling their _fix_up() method.
Note: This is called by MetaModel, but may als... |
Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to address subproperties of structured
properties).
Raises:
In... |
Create a Query object for this class.
Args:
distinct: Optional bool, short hand for group_by = projection.
*args: Used to apply an initial filter
**kwds: are passed to the Query() constructor.
Returns:
A Query object.
def _query(cls, *args, **kwds):
"""Create a Query object for th... |
Run a GQL query.
def _gql(cls, query_string, *args, **kwds):
"""Run a GQL query."""
from .query import gql # Import late to avoid circular imports.
return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string),
*args, **kwds) |
Write this entity to Cloud Datastore.
This is the asynchronous version of Model._put().
def _put_async(self, **ctx_options):
"""Write this entity to Cloud Datastore.
This is the asynchronous version of Model._put().
"""
if self._projection:
raise datastore_errors.BadRequestError('Cannot put... |
Transactionally retrieves an existing entity or creates a new one.
Positional Args:
name: Key name to retrieve or create.
Keyword Args:
namespace: Optional namespace.
app: Optional app ID.
parent: Parent entity key, if any.
context_options: ContextOptions object (not keyword args... |
Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
def _get_or_insert_async(*args, **kwds):
"""Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
"""... |
Allocates a range of key IDs for this model class.
Args:
size: Number of IDs to allocate. Either size or max can be specified,
not both.
max: Maximum ID to allocate. Either size or max can be specified,
not both.
parent: Parent key for which the IDs will be allocated.
**ctx_... |
Allocates a range of key IDs for this model class.
This is the asynchronous version of Model._allocate_ids().
def _allocate_ids_async(cls, size=None, max=None, parent=None,
**ctx_options):
"""Allocates a range of key IDs for this model class.
This is the asynchronous version of ... |
Returns an instance of Model class by ID.
This is really just a shorthand for Key(cls, id, ...).get().
Args:
id: A string or integer key ID.
parent: Optional parent key of the model to get.
namespace: Optional namespace.
app: Optional app ID.
**ctx_options: Context options.
... |
Returns an instance of Model class by ID (and app, namespace).
This is the asynchronous version of Model._get_by_id().
def _get_by_id_async(cls, id, parent=None, app=None, namespace=None,
**ctx_options):
"""Returns an instance of Model class by ID (and app, namespace).
This is the ... |
Checks whether a specific hook is in its default state.
Args:
cls: A ndb.model.Model class.
default_hook: Callable specified by ndb internally (do not override).
hook: The hook defined by a model class using _post_*_hook.
Raises:
TypeError if either the default hook or the tested hook ... |
Construct a Reference; the signature is the same as for Key.
def _ConstructReference(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=None):
"""Construct a Reference; the signature is the same as for Key."""
... |
Construct a Reference from a list of pairs.
If a Reference is passed in as the second argument, it is modified
in place. The app and namespace are set from the corresponding
keyword arguments, with the customary defaults.
def _ReferenceFromPairs(pairs, reference=None, app=None, namespace=None):
"""Construct ... |
Construct a Reference from a serialized Reference.
def _ReferenceFromSerialized(serialized):
"""Construct a Reference from a serialized Reference."""
if not isinstance(serialized, basestring):
raise TypeError('serialized must be a string; received %r' % serialized)
elif isinstance(serialized, unicode):
s... |
Decode a url-safe base64-encoded string.
This returns the decoded string.
def _DecodeUrlSafe(urlsafe):
"""Decode a url-safe base64-encoded string.
This returns the decoded string.
"""
if not isinstance(urlsafe, basestring):
raise TypeError('urlsafe must be a string; received %r' % urlsafe)
if isinsta... |
Construct a Reference; the signature is the same as for Key.
def _parse_from_ref(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=None):
"""Construct a Reference; the signature is the same as for Key."""
if c... |
Return a Key constructed from all but the last (kind, id) pairs.
If there is only one (kind, id) pair, return None.
def parent(self):
"""Return a Key constructed from all but the last (kind, id) pairs.
If there is only one (kind, id) pair, return None.
"""
pairs = self.__pairs
if len(pairs) <... |
Return the string id in the last (kind, id) pair, if any.
Returns:
A string id, or None if the key has an integer id or is incomplete.
def string_id(self):
"""Return the string id in the last (kind, id) pair, if any.
Returns:
A string id, or None if the key has an integer id or is incomplete.... |
Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomplete.
def integer_id(self):
"""Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomple... |
Return a tuple of alternating kind and id values.
def flat(self):
"""Return a tuple of alternating kind and id values."""
flat = []
for kind, id in self.__pairs:
flat.append(kind)
flat.append(id)
return tuple(flat) |
Return the Reference object for this Key.
This is a entity_pb.Reference instance -- a protocol buffer class
used by the lower-level API to the datastore.
NOTE: The caller should not mutate the return value.
def reference(self):
"""Return the Reference object for this Key.
This is a entity_pb.Ref... |
Return a url-safe string encoding this Key's Reference.
This string is compatible with other APIs and languages and with
the strings used to represent Keys in GQL and in the App Engine
Admin Console.
def urlsafe(self):
"""Return a url-safe string encoding this Key's Reference.
This string is comp... |
Return a Future whose result is the entity for this Key.
If no such entity exists, a Future is still returned, and the
Future's eventual return result be None.
def get_async(self, **ctx_options):
"""Return a Future whose result is the entity for this Key.
If no such entity exists, a Future is still r... |
Schedule deletion of the entity for this Key.
This returns a Future, whose result becomes available once the
deletion is complete. If no such entity exists, a Future is still
returned. In all cases the Future's result is None (i.e. there is
no way to tell whether the entity existed or not).
def dele... |
Add an exception that should not be logged.
The argument must be a subclass of Exception.
def add_flow_exception(exc):
"""Add an exception that should not be logged.
The argument must be a subclass of Exception.
"""
global _flow_exceptions
if not isinstance(exc, type) or not issubclass(exc, Exception):
... |
Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported.
def _init_flow_exceptions():
"""Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported.
"""
global _flow_exceptions
_flow... |
Public function to sleep some time.
Example:
yield tasklets.sleep(0.5) # Sleep for half a sec.
def sleep(dt):
"""Public function to sleep some time.
Example:
yield tasklets.sleep(0.5) # Sleep for half a sec.
"""
fut = Future('sleep(%.3f)' % dt)
eventloop.queue_call(dt, fut.set_result, None)
r... |
Helper to transfer result or errors from one Future to another.
def _transfer_result(fut1, fut2):
"""Helper to transfer result or errors from one Future to another."""
exc = fut1.get_exception()
if exc is not None:
tb = fut1.get_traceback()
fut2.set_exception(exc, tb)
else:
val = fut1.get_result()
... |
Decorator to run a function as a tasklet when called.
Use this to wrap a request handler function that will be called by
some web application framework (e.g. a Django view function or a
webapp.RequestHandler.get method).
def synctasklet(func):
"""Decorator to run a function as a tasklet when called.
Use th... |
A sync tasklet that sets a fresh default Context.
Use this for toplevel view functions such as
webapp.RequestHandler.get() or Django view functions.
def toplevel(func):
"""A sync tasklet that sets a fresh default Context.
Use this for toplevel view functions such as
webapp.RequestHandler.get() or Django vi... |
Creates a new context to connect to a remote Cloud Datastore instance.
This should only be used outside of Google App Engine.
Args:
app_id: The application id to connect to. This differs from the project
id as it may have an additional prefix, e.g. "s~" or "e~".
external_app_ids: A list of apps that... |
Internal helper to check a list of indexed fields.
Args:
indexed_fields: A list of names, possibly dotted names.
(A dotted name is a string containing names separated by dots,
e.g. 'foo.bar.baz'. An undotted name is a string containing no
dots, e.g. 'foo'.)
Returns:
A dict whose keys are undotted ... |
Construct a Model subclass corresponding to a Message subclass.
Args:
message_type: A Message subclass.
indexed_fields: A list of dotted and undotted field names.
**props: Additional properties with which to seed the class.
Returns:
A Model subclass whose properties correspond to those fields of
... |
Recursive helper for _to_base_type() to convert a message to an entity.
Args:
msg: A Message instance.
modelclass: A Model subclass.
Returns:
An instance of modelclass.
def _message_to_entity(msg, modelclass):
"""Recursive helper for _to_base_type() to convert a message to an entity.
Args:
m... |
Recursive helper for _from_base_type() to convert an entity to a message.
Args:
ent: A Model instance.
message_type: A Message subclass.
Returns:
An instance of message_type.
def _projected_entity_to_message(ent, message_type):
"""Recursive helper for _from_base_type() to convert an entity to a mes... |
Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._enum_type.
def _validate(self, value):
"""Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._enum_type.
"""
if not isinstance(value, self._enum_type):
raise TypeErr... |
Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type.
def _validate(self, msg):
"""Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type.
"""
if not isinstance(msg, self._message_type):
raise Ty... |
Convert a Message value to a Model instance (entity).
def _to_base_type(self, msg):
"""Convert a Message value to a Model instance (entity)."""
ent = _message_to_entity(msg, self._modelclass)
ent.blob_ = self._protocol_impl.encode_message(msg)
return ent |
Convert a Model instance (entity) to a Message value.
def _from_base_type(self, ent):
"""Convert a Model instance (entity) to a Message value."""
if ent._projection:
# Projection query result. Reconstitute the message from the fields.
return _projected_entity_to_message(ent, self._message_type)
... |
Compute and store a default value if necessary.
def _get_value(self, entity):
"""Compute and store a default value if necessary."""
value = super(_ClassKeyProperty, self)._get_value(entity)
if not value:
value = entity._class_key()
self._store_value(entity, value)
return value |
Override; called by Model._fix_up_properties().
Update the kind map as well as the class map, except for PolyModel
itself (its class key is empty). Note that the kind map will
contain entries for all classes in a PolyModel hierarchy; they all
have the same kind, but different class names. PolyModel c... |
Override.
Use the class map to give the entity the correct subclass.
def _from_pb(cls, pb, set_key=True, ent=None, key=None):
"""Override.
Use the class map to give the entity the correct subclass.
"""
prop_name = cls.class_._name
class_name = []
for plist in [pb.property_list(), pb.raw_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.