Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _make_ctx_options(ctx_options, config_cls=ContextOptions):
"""Helper to construct a ContextOptions object from keyword arguments.
Args:
ctx_options: A dict of keyword arguments.
config_cls: Optional Configuration class to use, default ContextOptions.
Note that either 'options' or 'config' can be use... |
def set_cache_policy(self, func):
"""Set the context cache policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should be cached. May be None.
"""
if func is None:
func = self.default_cache_policy
elif isinstance(fu... |
def _use_cache(self, key, options=None):
"""Return whether to use the context cache for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the key should be cached, False otherwise.
"""
flag = ContextOptions.use_cache(options)
if fl... |
def set_memcache_policy(self, func):
"""Set the memcache policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should be cached. May be None.
"""
if func is None:
func = self.default_memcache_policy
elif isinstance(f... |
def _use_memcache(self, key, options=None):
"""Return whether to use memcache for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the key should be cached in memcache, False otherwise.
"""
flag = ContextOptions.use_memcache(options)
... |
def default_datastore_policy(key):
"""Default datastore policy.
This defers to _use_datastore on the Model class.
Args:
key: Key instance.
Returns:
A bool or None.
"""
flag = None
if key is not None:
modelclass = model.Model._kind_map.get(key.kind())
if modelclass ... |
def set_datastore_policy(self, func):
"""Set the context datastore policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should use the datastore. May be None.
"""
if func is None:
func = self.default_datastore_policy
... |
def _use_datastore(self, key, options=None):
"""Return whether to use the datastore for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the datastore should be used, False otherwise.
"""
flag = ContextOptions.use_datastore(options)
... |
def default_memcache_timeout_policy(key):
"""Default memcache timeout policy.
This defers to _memcache_timeout on the Model class.
Args:
key: Key instance.
Returns:
Memcache timeout to use (integer), or None.
"""
timeout = None
if key is not None and isinstance(key, model.Key)... |
def set_memcache_timeout_policy(self, func):
"""Set the policy function for memcache timeout (expiration).
Args:
func: A function that accepts a key instance as argument and returns
an integer indicating the desired memcache timeout. May be None.
If the function returns 0 it implies the def... |
def _get_memcache_timeout(self, key, options=None):
"""Return the memcache timeout (expiration) for this key."""
timeout = ContextOptions.memcache_timeout(options)
if timeout is None:
timeout = self._memcache_timeout_policy(key)
if timeout is None:
timeout = ContextOptions.memcache_timeout(s... |
def _load_from_cache_if_available(self, key):
"""Returns a cached Model instance given the entity key if available.
Args:
key: Key instance.
Returns:
A Model instance if the key exists in the cache.
"""
if key in self._cache:
entity = self._cache[key] # May be None, meaning "doe... |
def get(self, key, **ctx_options):
"""Return a Model instance given the entity key.
It will use the context cache if the cache policy for the given
key is enabled.
Args:
key: Key instance.
**ctx_options: Context options.
Returns:
A Model instance if the key exists in the datasto... |
def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were regis... |
def get_nickname(userid):
"""Return a Future for a nickname from an account."""
account = yield get_account(userid)
if not account:
nickname = 'Unregistered'
else:
nickname = account.nickname or account.email
raise ndb.Return(nickname) |
def mark_done(task_id):
"""Marks a task as done.
Args:
task_id: The integer id of the task to update.
Raises:
ValueError: if the requested task doesn't exist.
"""
task = Task.get_by_id(task_id)
if task is None:
raise ValueError('Task with id %d does not exist' % task_id)
task.done = True
t... |
def format_tasks(tasks):
"""Converts a list of tasks to a list of string representations.
Args:
tasks: A list of the tasks to convert.
Returns:
A list of string formatted tasks.
"""
return ['%d : %s (%s)' % (task.key.id(),
task.description,
('do... |
def handle_command(command):
"""Accepts a string command and performs an action.
Args:
command: the command to run as a string.
"""
try:
cmds = command.split(None, 1)
cmd = cmds[0]
if cmd == 'new':
add_task(get_arg(cmds))
elif cmd == 'done':
mark_done(int(get_arg(cmds)))
eli... |
def delete_async(blob_key, **options):
"""Async version of delete()."""
if not isinstance(blob_key, (basestring, BlobKey)):
raise TypeError('Expected blob key, got %r' % (blob_key,))
rpc = blobstore.create_rpc(**options)
yield blobstore.delete_async(blob_key, rpc=rpc) |
def delete_multi_async(blob_keys, **options):
"""Async version of delete_multi()."""
if isinstance(blob_keys, (basestring, BlobKey)):
raise TypeError('Expected a list, got %r' % (blob_key,))
rpc = blobstore.create_rpc(**options)
yield blobstore.delete_async(blob_keys, rpc=rpc) |
def create_upload_url(success_path,
max_bytes_per_blob=None,
max_bytes_total=None,
**options):
"""Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_... |
def create_upload_url_async(success_path,
max_bytes_per_blob=None,
max_bytes_total=None,
**options):
"""Async version of create_upload_url()."""
rpc = blobstore.create_rpc(**options)
rpc = blobstore.create_upload_url_async(success... |
def parse_blob_info(field_storage):
"""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:
BlobInfoParseErro... |
def fetch_data(blob, start_index, end_index, **options):
"""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... |
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 rpc
raise tasklets.Return(resu... |
def get(cls, blob_key, **ctx_options):
"""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 s... |
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.get_by_id_async(str(blob... |
def get_multi(cls, blob_keys, **ctx_options):
"""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.
"""
futs = cls.get_multi_async(blob_ke... |
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:
raise TypeError('Parent is not sup... |
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() |
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_FETCH_SIZE].
"""
read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE)
self.__buffer = fetch_data(self.__blob_key, self._... |
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 |
def make_connection(config=None, default_model=None,
_api_version=datastore_rpc._DATASTORE_V3,
_id_resolver=None):
"""Create a new Connection object with the right adapter.
Optionally you can pass in a datastore_rpc.Configuration object.
"""
return datastore_rpc.Connecti... |
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_gaiaid().decode('utf-8')
obfuscated_gaiaid = unicode(obfuscated_g... |
def _date_to_datetime(value):
"""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.
"""
if not isinstance(value, datetime.date):
raise TypeError('Cannot convert to datetime expected date value; '
... |
def _time_to_datetime(value):
"""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.
"""
if not isinstance(value, datetime.time):
raise TypeError('Cannot convert to datetime expected time value; '
... |
def transactional(func, args, kwds, **options):
"""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
d... |
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 transaction_async(func, **options) |
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.tasklet(func)
return transactional_async.wrapped_decorator(func, args, kwds, **options) |
def non_transactional(func, args, kwds, allow_existing=True):
"""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 exce... |
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 |
def _comparison(self, op, value):
"""Internal helper for comparison operators.
Args:
op: The operator ('=', '<' etc.).
Returns:
A FilterNode instance representing the requested comparison.
"""
# NOTE: This is also used by query.gql().
if not self._indexed:
raise datastore_err... |
def _IN(self, value):
"""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... |
def _do_validate(self, value):
"""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 no... |
def _fix_up(self, cls, code_name):
"""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 assigne... |
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 the value
should be a list.
"""
if entity._projection:
raise ReadonlyPropertyError(
'You cannot set property values of a proje... |
def _retrieve_value(self, entity, default=None):
"""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 transformati... |
def _get_base_value_unwrapped_as_list(self, entity):
"""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 N... |
def _opt_call_from_base_type(self, value):
"""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.
"""
if isinstance(value, _BaseValue):
value = self._call_from_base_type(value... |
def _opt_call_to_base_type(self, value):
"""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.
"""
if not isinstance(value, _BaseValue):
value = _B... |
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 property's class.
"""
methods = self._find_methods('_from_base_type', reverse=True)
call = self._apply_list(methods)
return call(va... |
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 the
property's class.
"""
methods = self._find_methods('_validate', '_to_base_type')
call = self._apply_list(methods)
return call(v... |
def _call_shallow_validation(self, value):
"""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 ->
... |
def _find_methods(cls, *names, **kwds):
"""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 ... |
def _apply_list(self, methods):
"""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 call(value):
for method in methods:
... |
def _apply_to_values(self, entity, function):
"""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... |
def _get_value(self, entity):
"""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.
"""
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(... |
def _delete_value(self, entity):
"""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).
"""
if... |
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 (not self._required or
((self._has_value(entity) or self._default is not None) and
self._get_value(entity... |
def _serialize(self, entity, pb, prefix='', parent_repeated=False,
projection=None):
"""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 Enti... |
def _deserialize(self, entity, p, unused_depth=1):
"""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... |
def _check_property(self, rest=None, require_indexed=True):
"""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... |
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 |
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.
return super(StructuredProperty, self)._get_value(entity)
... |
def _check_property(self, rest=None, require_indexed=True):
"""Override for Property._check_property().
Raises:
InvalidPropertyError if no subproperty is specified or if something
is wrong with the subproperty.
"""
if not rest:
raise InvalidPropertyError(
'Structured propert... |
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)
if not isinstance(obj, Property) or isinstance(obj, ModelKey):
... |
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) # Raises AttributeError for unknown properties.
if not isinstance(prop, Property... |
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()
if not prop._is_initialized(self)) |
def _check_initialized(self):
"""Internal helper to check for uninitialized properties.
Raises:
BadValueError if it finds any.
"""
baddies = self._find_uninitialized()
if baddies:
raise datastore_errors.BadValueError(
'Entity has uninitialized properties: %s' % ', '.join(baddi... |
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
cls._kind_map.clear()
cls._kind_map.up... |
def _lookup_model(cls, kind, default_model=None):
"""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:
Ki... |
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. '
'%s is not %s' % (self.__class__.__name... |
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 set_key:
# TODO: Move the key stuff into ModelAdapter.enti... |
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.reference()
pb.mutable_key().CopyFrom(ref)
... |
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)
if ent is None:
ent = cls()
# A key passed in override... |
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.
# Assume it is a None written for a missing value.
# (It coul... |
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) |
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, _BaseValue(Expando()))
else:
compressed... |
def _to_dict(self, include=None, exclude=None):
"""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 exc... |
def _fix_up_properties(cls):
"""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.
"""
# Verify that _get_kind() returns an 8-bit string.
kind = cls._get_kind()
if not isinstan... |
def _check_properties(cls, property_names, require_indexed=True):
"""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 addre... |
def _query(cls, *args, **kwds):
"""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.
"""
# Validating dist... |
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) |
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 a partial entity')
from . import tasklets
ctx = tasklets.get_context()
self._prep... |
def _get_or_insert(*args, **kwds):
"""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_option... |
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().
"""
# NOTE: The signature is really weird here because we want to support
# models with properties named e.g. 'cls' or 'name'.
... |
def _allocate_ids(cls, size=None, max=None, parent=None, **ctx_options):
"""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 ... |
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 Model._allocate_ids().
"""
from . import tasklets
ctx = tasklets.get_context()
cls._pre_allocate_ids... |
def _get_by_id(cls, id, parent=None, **ctx_options):
"""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: ... |
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 asynchronous version of Model._get_by_id().
"""
key = Key(cls._get_kind(), id, parent=parent, app=app, namespace=name... |
def _is_default_hook(default_hook, hook):
"""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:
TypeErr... |
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."""
if cls is not Key:
raise TypeError('Cannot construct Key r... |
def _ReferenceFromPairs(pairs, reference=None, app=None, namespace=None):
"""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.
"""
if ... |
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):
serialized = serialized.encode('utf8')
return entit... |
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 isinstance(urlsafe, unicode):
urlsafe = urlsafe.encode('utf8')
mod = len(urlsaf... |
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 cls is not Key:
raise TypeError('Cannot construct Key ref... |
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) <= 1:
return None
return Key(pairs=pairs[:-1], app=self.__app, namespace=self.__namespace) |
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.
"""
id = self.id()
if not isinstance(id, basestring):
id = None
return id |
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 incomplete.
"""
id = self.id()
if not isinstance(id, (int, long)):
id = None
return id |
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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.