repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | parse_blob_info | 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:
BlobInfoParseError when provided field_storage does not contain enough
information to construct a BlobInfo object.
"""
if field_storage is None:
return None
field_name = field_storage.name
def get_value(dct, name):
value = dct.get(name, None)
if value is None:
raise BlobInfoParseError(
'Field %s has no %s.' % (field_name, name))
return value
filename = get_value(field_storage.disposition_options, 'filename')
blob_key_str = get_value(field_storage.type_options, 'blob-key')
blob_key = BlobKey(blob_key_str)
upload_content = email.message_from_file(field_storage.file)
content_type = get_value(upload_content, 'content-type')
size = get_value(upload_content, 'content-length')
creation_string = get_value(upload_content, UPLOAD_INFO_CREATION_HEADER)
md5_hash_encoded = get_value(upload_content, 'content-md5')
md5_hash = base64.urlsafe_b64decode(md5_hash_encoded)
try:
size = int(size)
except (TypeError, ValueError):
raise BlobInfoParseError(
'%s is not a valid value for %s size.' % (size, field_name))
try:
creation = blobstore._parse_creation(creation_string, field_name)
except blobstore._CreationFormatError, err:
raise BlobInfoParseError(str(err))
return BlobInfo(id=blob_key_str,
content_type=content_type,
creation=creation,
filename=filename,
size=size,
md5_hash=md5_hash,
) | python | 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:
BlobInfoParseError when provided field_storage does not contain enough
information to construct a BlobInfo object.
"""
if field_storage is None:
return None
field_name = field_storage.name
def get_value(dct, name):
value = dct.get(name, None)
if value is None:
raise BlobInfoParseError(
'Field %s has no %s.' % (field_name, name))
return value
filename = get_value(field_storage.disposition_options, 'filename')
blob_key_str = get_value(field_storage.type_options, 'blob-key')
blob_key = BlobKey(blob_key_str)
upload_content = email.message_from_file(field_storage.file)
content_type = get_value(upload_content, 'content-type')
size = get_value(upload_content, 'content-length')
creation_string = get_value(upload_content, UPLOAD_INFO_CREATION_HEADER)
md5_hash_encoded = get_value(upload_content, 'content-md5')
md5_hash = base64.urlsafe_b64decode(md5_hash_encoded)
try:
size = int(size)
except (TypeError, ValueError):
raise BlobInfoParseError(
'%s is not a valid value for %s size.' % (size, field_name))
try:
creation = blobstore._parse_creation(creation_string, field_name)
except blobstore._CreationFormatError, err:
raise BlobInfoParseError(str(err))
return BlobInfo(id=blob_key_str,
content_type=content_type,
creation=creation,
filename=filename,
size=size,
md5_hash=md5_hash,
) | [
"def",
"parse_blob_info",
"(",
"field_storage",
")",
":",
"if",
"field_storage",
"is",
"None",
":",
"return",
"None",
"field_name",
"=",
"field_storage",
".",
"name",
"def",
"get_value",
"(",
"dct",
",",
"name",
")",
":",
"value",
"=",
"dct",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"BlobInfoParseError",
"(",
"'Field %s has no %s.'",
"%",
"(",
"field_name",
",",
"name",
")",
")",
"return",
"value",
"filename",
"=",
"get_value",
"(",
"field_storage",
".",
"disposition_options",
",",
"'filename'",
")",
"blob_key_str",
"=",
"get_value",
"(",
"field_storage",
".",
"type_options",
",",
"'blob-key'",
")",
"blob_key",
"=",
"BlobKey",
"(",
"blob_key_str",
")",
"upload_content",
"=",
"email",
".",
"message_from_file",
"(",
"field_storage",
".",
"file",
")",
"content_type",
"=",
"get_value",
"(",
"upload_content",
",",
"'content-type'",
")",
"size",
"=",
"get_value",
"(",
"upload_content",
",",
"'content-length'",
")",
"creation_string",
"=",
"get_value",
"(",
"upload_content",
",",
"UPLOAD_INFO_CREATION_HEADER",
")",
"md5_hash_encoded",
"=",
"get_value",
"(",
"upload_content",
",",
"'content-md5'",
")",
"md5_hash",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"md5_hash_encoded",
")",
"try",
":",
"size",
"=",
"int",
"(",
"size",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"BlobInfoParseError",
"(",
"'%s is not a valid value for %s size.'",
"%",
"(",
"size",
",",
"field_name",
")",
")",
"try",
":",
"creation",
"=",
"blobstore",
".",
"_parse_creation",
"(",
"creation_string",
",",
"field_name",
")",
"except",
"blobstore",
".",
"_CreationFormatError",
",",
"err",
":",
"raise",
"BlobInfoParseError",
"(",
"str",
"(",
"err",
")",
")",
"return",
"BlobInfo",
"(",
"id",
"=",
"blob_key_str",
",",
"content_type",
"=",
"content_type",
",",
"creation",
"=",
"creation",
",",
"filename",
"=",
"filename",
",",
"size",
"=",
"size",
",",
"md5_hash",
"=",
"md5_hash",
",",
")"
] | 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 contain enough
information to construct a BlobInfo object. | [
"Parse",
"a",
"BlobInfo",
"record",
"from",
"file",
"upload",
"field_storage",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L346-L400 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | fetch_data | 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 be
a smaller size than requested. Requesting a fragment which is entirely
outside the boundaries of the blob will return empty string. Attempting
to fetch a negative index will raise an exception.
Args:
blob: BlobInfo, BlobKey, str or unicode representation of BlobKey of
blob to fetch data from.
start_index: Start index of blob data to fetch. May not be negative.
end_index: End index (inclusive) of blob data to fetch. Must be
>= start_index.
**options: Options for create_rpc().
Returns:
str containing partial data of blob. If the indexes are legal but outside
the boundaries of the blob, will return empty string.
Raises:
TypeError if start_index or end_index are not indexes. Also when blob
is not a string, BlobKey or BlobInfo.
DataIndexOutOfRangeError when start_index < 0 or end_index < start_index.
BlobFetchSizeTooLargeError when request blob fragment is larger than
MAX_BLOB_FETCH_SIZE.
BlobNotFoundError when blob does not exist.
"""
fut = fetch_data_async(blob, start_index, end_index, **options)
return fut.get_result() | python | 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 be
a smaller size than requested. Requesting a fragment which is entirely
outside the boundaries of the blob will return empty string. Attempting
to fetch a negative index will raise an exception.
Args:
blob: BlobInfo, BlobKey, str or unicode representation of BlobKey of
blob to fetch data from.
start_index: Start index of blob data to fetch. May not be negative.
end_index: End index (inclusive) of blob data to fetch. Must be
>= start_index.
**options: Options for create_rpc().
Returns:
str containing partial data of blob. If the indexes are legal but outside
the boundaries of the blob, will return empty string.
Raises:
TypeError if start_index or end_index are not indexes. Also when blob
is not a string, BlobKey or BlobInfo.
DataIndexOutOfRangeError when start_index < 0 or end_index < start_index.
BlobFetchSizeTooLargeError when request blob fragment is larger than
MAX_BLOB_FETCH_SIZE.
BlobNotFoundError when blob does not exist.
"""
fut = fetch_data_async(blob, start_index, end_index, **options)
return fut.get_result() | [
"def",
"fetch_data",
"(",
"blob",
",",
"start_index",
",",
"end_index",
",",
"*",
"*",
"options",
")",
":",
"fut",
"=",
"fetch_data_async",
"(",
"blob",
",",
"start_index",
",",
"end_index",
",",
"*",
"*",
"options",
")",
"return",
"fut",
".",
"get_result",
"(",
")"
] | 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 which is entirely
outside the boundaries of the blob will return empty string. Attempting
to fetch a negative index will raise an exception.
Args:
blob: BlobInfo, BlobKey, str or unicode representation of BlobKey of
blob to fetch data from.
start_index: Start index of blob data to fetch. May not be negative.
end_index: End index (inclusive) of blob data to fetch. Must be
>= start_index.
**options: Options for create_rpc().
Returns:
str containing partial data of blob. If the indexes are legal but outside
the boundaries of the blob, will return empty string.
Raises:
TypeError if start_index or end_index are not indexes. Also when blob
is not a string, BlobKey or BlobInfo.
DataIndexOutOfRangeError when start_index < 0 or end_index < start_index.
BlobFetchSizeTooLargeError when request blob fragment is larger than
MAX_BLOB_FETCH_SIZE.
BlobNotFoundError when blob does not exist. | [
"Fetch",
"data",
"for",
"blob",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L403-L434 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | fetch_data_async | 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(result) | python | 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(result) | [
"def",
"fetch_data_async",
"(",
"blob",
",",
"start_index",
",",
"end_index",
",",
"*",
"*",
"options",
")",
":",
"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",
"(",
"result",
")"
] | Async version of fetch_data(). | [
"Async",
"version",
"of",
"fetch_data",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L438-L445 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobInfo.get | 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 such entity, returns None.
"""
fut = cls.get_async(blob_key, **ctx_options)
return fut.get_result() | python | 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 such entity, returns None.
"""
fut = cls.get_async(blob_key, **ctx_options)
return fut.get_result() | [
"def",
"get",
"(",
"cls",
",",
"blob_key",
",",
"*",
"*",
"ctx_options",
")",
":",
"fut",
"=",
"cls",
".",
"get_async",
"(",
"blob_key",
",",
"*",
"*",
"ctx_options",
")",
"return",
"fut",
".",
"get_result",
"(",
")"
] | 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. | [
"Retrieve",
"a",
"BlobInfo",
"by",
"key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L167-L179 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobInfo.get_async | 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_key), **ctx_options) | python | 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_key), **ctx_options) | [
"def",
"get_async",
"(",
"cls",
",",
"blob_key",
",",
"*",
"*",
"ctx_options",
")",
":",
"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_key",
")",
",",
"*",
"*",
"ctx_options",
")"
] | Async version of get(). | [
"Async",
"version",
"of",
"get",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L182-L188 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobInfo.get_multi | 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_keys, **ctx_options)
return [fut.get_result() for fut in futs] | python | 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_keys, **ctx_options)
return [fut.get_result() for fut in futs] | [
"def",
"get_multi",
"(",
"cls",
",",
"blob_keys",
",",
"*",
"*",
"ctx_options",
")",
":",
"futs",
"=",
"cls",
".",
"get_multi_async",
"(",
"blob_keys",
",",
"*",
"*",
"ctx_options",
")",
"return",
"[",
"fut",
".",
"get_result",
"(",
")",
"for",
"fut",
"in",
"futs",
"]"
] | 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. | [
"Multi",
"-",
"key",
"version",
"of",
"get",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L191-L202 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobInfo.get_multi_async | 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 supported')
blob_key_strs = map(str, blob_keys)
keys = [model.Key(BLOB_INFO_KIND, id) for id in blob_key_strs]
return model.get_multi_async(keys, **ctx_options) | python | 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 supported')
blob_key_strs = map(str, blob_keys)
keys = [model.Key(BLOB_INFO_KIND, id) for id in blob_key_strs]
return model.get_multi_async(keys, **ctx_options) | [
"def",
"get_multi_async",
"(",
"cls",
",",
"blob_keys",
",",
"*",
"*",
"ctx_options",
")",
":",
"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 supported'",
")",
"blob_key_strs",
"=",
"map",
"(",
"str",
",",
"blob_keys",
")",
"keys",
"=",
"[",
"model",
".",
"Key",
"(",
"BLOB_INFO_KIND",
",",
"id",
")",
"for",
"id",
"in",
"blob_key_strs",
"]",
"return",
"model",
".",
"get_multi_async",
"(",
"keys",
",",
"*",
"*",
"ctx_options",
")"
] | Async version of get_multi(). | [
"Async",
"version",
"of",
"get_multi",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L205-L214 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobInfo.delete | 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() | python | 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",
"delete",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"fut",
"=",
"delete_async",
"(",
"self",
".",
"key",
"(",
")",
",",
"*",
"*",
"options",
")",
"fut",
".",
"get_result",
"(",
")"
] | Permanently delete this blob from Blobstore.
Args:
**options: Options for create_rpc(). | [
"Permanently",
"delete",
"this",
"blob",
"from",
"Blobstore",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L230-L237 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobReader.__fill_buffer | 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.__position,
self.__position + read_size - 1)
self.__buffer_position = 0
self.__eof = len(self.__buffer) < read_size | python | 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.__position,
self.__position + read_size - 1)
self.__buffer_position = 0
self.__eof = len(self.__buffer) < read_size | [
"def",
"__fill_buffer",
"(",
"self",
",",
"size",
"=",
"0",
")",
":",
"read_size",
"=",
"min",
"(",
"max",
"(",
"size",
",",
"self",
".",
"__buffer_size",
")",
",",
"MAX_BLOB_FETCH_SIZE",
")",
"self",
".",
"__buffer",
"=",
"fetch_data",
"(",
"self",
".",
"__blob_key",
",",
"self",
".",
"__position",
",",
"self",
".",
"__position",
"+",
"read_size",
"-",
"1",
")",
"self",
".",
"__buffer_position",
"=",
"0",
"self",
".",
"__eof",
"=",
"len",
"(",
"self",
".",
"__buffer",
")",
"<",
"read_size"
] | Fills the internal buffer.
Args:
size: Number of bytes to read. Will be clamped to
[self.__buffer_size, MAX_BLOB_FETCH_SIZE]. | [
"Fills",
"the",
"internal",
"buffer",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L455-L467 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/blobstore.py | BlobReader.blob_info | 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 | python | 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",
"blob_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__blob_info",
":",
"self",
".",
"__blob_info",
"=",
"BlobInfo",
".",
"get",
"(",
"self",
".",
"__blob_key",
")",
"return",
"self",
".",
"__blob_info"
] | Returns the BlobInfo for this file. | [
"Returns",
"the",
"BlobInfo",
"for",
"this",
"file",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/blobstore.py#L470-L474 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | make_connection | 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.Connection(
adapter=ModelAdapter(default_model, id_resolver=_id_resolver),
config=config,
_api_version=_api_version) | python | 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.Connection(
adapter=ModelAdapter(default_model, id_resolver=_id_resolver),
config=config,
_api_version=_api_version) | [
"def",
"make_connection",
"(",
"config",
"=",
"None",
",",
"default_model",
"=",
"None",
",",
"_api_version",
"=",
"datastore_rpc",
".",
"_DATASTORE_V3",
",",
"_id_resolver",
"=",
"None",
")",
":",
"return",
"datastore_rpc",
".",
"Connection",
"(",
"adapter",
"=",
"ModelAdapter",
"(",
"default_model",
",",
"id_resolver",
"=",
"_id_resolver",
")",
",",
"config",
"=",
"config",
",",
"_api_version",
"=",
"_api_version",
")"
] | Create a new Connection object with the right adapter.
Optionally you can pass in a datastore_rpc.Configuration object. | [
"Create",
"a",
"new",
"Connection",
"object",
"with",
"the",
"right",
"adapter",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L716-L726 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | _unpack_user | 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_gaiaid)
federated_identity = None
if uv.has_federated_identity():
federated_identity = unicode(
uv.federated_identity().decode('utf-8'))
value = users.User(email=email,
_auth_domain=auth_domain,
_user_id=obfuscated_gaiaid,
federated_identity=federated_identity)
return value | python | 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_gaiaid)
federated_identity = None
if uv.has_federated_identity():
federated_identity = unicode(
uv.federated_identity().decode('utf-8'))
value = users.User(email=email,
_auth_domain=auth_domain,
_user_id=obfuscated_gaiaid,
federated_identity=federated_identity)
return value | [
"def",
"_unpack_user",
"(",
"v",
")",
":",
"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_gaiaid",
")",
"federated_identity",
"=",
"None",
"if",
"uv",
".",
"has_federated_identity",
"(",
")",
":",
"federated_identity",
"=",
"unicode",
"(",
"uv",
".",
"federated_identity",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"value",
"=",
"users",
".",
"User",
"(",
"email",
"=",
"email",
",",
"_auth_domain",
"=",
"auth_domain",
",",
"_user_id",
"=",
"obfuscated_gaiaid",
",",
"federated_identity",
"=",
"federated_identity",
")",
"return",
"value"
] | Internal helper to unpack a User value from a protocol buffer. | [
"Internal",
"helper",
"to",
"unpack",
"a",
"User",
"value",
"from",
"a",
"protocol",
"buffer",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1838-L1855 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | _date_to_datetime | 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; '
'received %s' % value)
return datetime.datetime(value.year, value.month, value.day) | python | 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; '
'received %s' % value)
return datetime.datetime(value.year, value.month, value.day) | [
"def",
"_date_to_datetime",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot convert to datetime expected date value; '",
"'received %s'",
"%",
"value",
")",
"return",
"datetime",
".",
"datetime",
"(",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
".",
"day",
")"
] | 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. | [
"Convert",
"a",
"date",
"to",
"a",
"datetime",
"for",
"Cloud",
"Datastore",
"storage",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2142-L2154 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | _time_to_datetime | 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; '
'received %s' % value)
return datetime.datetime(1970, 1, 1,
value.hour, value.minute, value.second,
value.microsecond) | python | 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; '
'received %s' % value)
return datetime.datetime(1970, 1, 1,
value.hour, value.minute, value.second,
value.microsecond) | [
"def",
"_time_to_datetime",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot convert to datetime expected time value; '",
"'received %s'",
"%",
"value",
")",
"return",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"value",
".",
"hour",
",",
"value",
".",
"minute",
",",
"value",
".",
"second",
",",
"value",
".",
"microsecond",
")"
] | 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. | [
"Convert",
"a",
"time",
"to",
"a",
"datetime",
"for",
"Cloud",
"Datastore",
"storage",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2157-L2171 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | transactional | 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
def callback(arg):
...
(2) With options:
@transactional(retries=1)
def callback(arg):
...
"""
return transactional_async.wrapped_decorator(
func, args, kwds, **options).get_result() | python | 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
def callback(arg):
...
(2) With options:
@transactional(retries=1)
def callback(arg):
...
"""
return transactional_async.wrapped_decorator(
func, args, kwds, **options).get_result() | [
"def",
"transactional",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")",
":",
"return",
"transactional_async",
".",
"wrapped_decorator",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")",
".",
"get_result",
"(",
")"
] | 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:
@transactional(retries=1)
def callback(arg):
... | [
"Decorator",
"to",
"make",
"a",
"function",
"automatically",
"run",
"in",
"a",
"transaction",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3821-L3841 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | transactional_async | 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) | python | 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_async",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")",
":",
"options",
".",
"setdefault",
"(",
"'propagation'",
",",
"datastore_rpc",
".",
"TransactionOptions",
".",
"ALLOWED",
")",
"if",
"args",
"or",
"kwds",
":",
"return",
"transaction_async",
"(",
"lambda",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
",",
"*",
"*",
"options",
")",
"return",
"transaction_async",
"(",
"func",
",",
"*",
"*",
"options",
")"
] | The async version of @ndb.transaction. | [
"The",
"async",
"version",
"of"
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3845-L3850 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | transactional_tasklet | 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) | python | 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",
"transactional_tasklet",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")",
":",
"from",
".",
"import",
"tasklets",
"func",
"=",
"tasklets",
".",
"tasklet",
"(",
"func",
")",
"return",
"transactional_async",
".",
"wrapped_decorator",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")"
] | The async version of @ndb.transaction.
Will return the result of the wrapped function as a Future. | [
"The",
"async",
"version",
"of",
"@ndb",
".",
"transaction",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3854-L3861 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | non_transactional | 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 exception if called from within
a transaction. If true, temporarily re-establish the
previous non-transactional context. Defaults to True.
This supports two forms, similar to transactional().
Returns:
A wrapper for the decorated function that ensures it runs outside a
transaction.
"""
from . import tasklets
ctx = tasklets.get_context()
if not ctx.in_transaction():
return func(*args, **kwds)
if not allow_existing:
raise datastore_errors.BadRequestError(
'%s cannot be called within a transaction.' % func.__name__)
save_ctx = ctx
while ctx.in_transaction():
ctx = ctx._parent_context
if ctx is None:
raise datastore_errors.BadRequestError(
'Context without non-transactional ancestor')
save_ds_conn = datastore._GetConnection()
try:
if hasattr(save_ctx, '_old_ds_conn'):
datastore._SetConnection(save_ctx._old_ds_conn)
tasklets.set_context(ctx)
return func(*args, **kwds)
finally:
tasklets.set_context(save_ctx)
datastore._SetConnection(save_ds_conn) | python | 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 exception if called from within
a transaction. If true, temporarily re-establish the
previous non-transactional context. Defaults to True.
This supports two forms, similar to transactional().
Returns:
A wrapper for the decorated function that ensures it runs outside a
transaction.
"""
from . import tasklets
ctx = tasklets.get_context()
if not ctx.in_transaction():
return func(*args, **kwds)
if not allow_existing:
raise datastore_errors.BadRequestError(
'%s cannot be called within a transaction.' % func.__name__)
save_ctx = ctx
while ctx.in_transaction():
ctx = ctx._parent_context
if ctx is None:
raise datastore_errors.BadRequestError(
'Context without non-transactional ancestor')
save_ds_conn = datastore._GetConnection()
try:
if hasattr(save_ctx, '_old_ds_conn'):
datastore._SetConnection(save_ctx._old_ds_conn)
tasklets.set_context(ctx)
return func(*args, **kwds)
finally:
tasklets.set_context(save_ctx)
datastore._SetConnection(save_ds_conn) | [
"def",
"non_transactional",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"allow_existing",
"=",
"True",
")",
":",
"from",
".",
"import",
"tasklets",
"ctx",
"=",
"tasklets",
".",
"get_context",
"(",
")",
"if",
"not",
"ctx",
".",
"in_transaction",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"if",
"not",
"allow_existing",
":",
"raise",
"datastore_errors",
".",
"BadRequestError",
"(",
"'%s cannot be called within a transaction.'",
"%",
"func",
".",
"__name__",
")",
"save_ctx",
"=",
"ctx",
"while",
"ctx",
".",
"in_transaction",
"(",
")",
":",
"ctx",
"=",
"ctx",
".",
"_parent_context",
"if",
"ctx",
"is",
"None",
":",
"raise",
"datastore_errors",
".",
"BadRequestError",
"(",
"'Context without non-transactional ancestor'",
")",
"save_ds_conn",
"=",
"datastore",
".",
"_GetConnection",
"(",
")",
"try",
":",
"if",
"hasattr",
"(",
"save_ctx",
",",
"'_old_ds_conn'",
")",
":",
"datastore",
".",
"_SetConnection",
"(",
"save_ctx",
".",
"_old_ds_conn",
")",
"tasklets",
".",
"set_context",
"(",
"ctx",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"finally",
":",
"tasklets",
".",
"set_context",
"(",
"save_ctx",
")",
"datastore",
".",
"_SetConnection",
"(",
"save_ds_conn",
")"
] | 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, temporarily re-establish the
previous non-transactional context. Defaults to True.
This supports two forms, similar to transactional().
Returns:
A wrapper for the decorated function that ensures it runs outside a
transaction. | [
"A",
"decorator",
"that",
"ensures",
"a",
"function",
"is",
"run",
"outside",
"a",
"transaction",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3865-L3903 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | _NestedCounter._set | 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 | python | 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",
"_set",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__is_parent_node",
"(",
")",
":",
"for",
"child",
"in",
"self",
".",
"__sub_counters",
".",
"itervalues",
"(",
")",
":",
"child",
".",
"_set",
"(",
"value",
")",
"else",
":",
"self",
".",
"__counter",
"=",
"value"
] | Updates all descendants to a specified value. | [
"Updates",
"all",
"descendants",
"to",
"a",
"specified",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L487-L493 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._comparison | 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_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if value is not None:
value = self._do_validate(value)
value = self._call_to_base_type(value)
value = self._datastore_type(value)
return FilterNode(self._name, op, value) | python | 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_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if value is not None:
value = self._do_validate(value)
value = self._call_to_base_type(value)
value = self._datastore_type(value)
return FilterNode(self._name, op, value) | [
"def",
"_comparison",
"(",
"self",
",",
"op",
",",
"value",
")",
":",
"# NOTE: This is also used by query.gql().",
"if",
"not",
"self",
".",
"_indexed",
":",
"raise",
"datastore_errors",
".",
"BadFilterError",
"(",
"'Cannot query for unindexed property %s'",
"%",
"self",
".",
"_name",
")",
"from",
".",
"query",
"import",
"FilterNode",
"# Import late to avoid circular imports.",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"_do_validate",
"(",
"value",
")",
"value",
"=",
"self",
".",
"_call_to_base_type",
"(",
"value",
")",
"value",
"=",
"self",
".",
"_datastore_type",
"(",
"value",
")",
"return",
"FilterNode",
"(",
"self",
".",
"_name",
",",
"op",
",",
"value",
")"
] | Internal helper for comparison operators.
Args:
op: The operator ('=', '<' etc.).
Returns:
A FilterNode instance representing the requested comparison. | [
"Internal",
"helper",
"for",
"comparison",
"operators",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L972-L990 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._IN | 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
as .IN(); ._IN() is provided for the case you have a
StructuredProperty with a model that has a Property named IN.
"""
if not self._indexed:
raise datastore_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadArgumentError(
'Expected list, tuple or set, got %r' % (value,))
values = []
for val in value:
if val is not None:
val = self._do_validate(val)
val = self._call_to_base_type(val)
val = self._datastore_type(val)
values.append(val)
return FilterNode(self._name, 'in', values) | python | 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
as .IN(); ._IN() is provided for the case you have a
StructuredProperty with a model that has a Property named IN.
"""
if not self._indexed:
raise datastore_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadArgumentError(
'Expected list, tuple or set, got %r' % (value,))
values = []
for val in value:
if val is not None:
val = self._do_validate(val)
val = self._call_to_base_type(val)
val = self._datastore_type(val)
values.append(val)
return FilterNode(self._name, 'in', values) | [
"def",
"_IN",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_indexed",
":",
"raise",
"datastore_errors",
".",
"BadFilterError",
"(",
"'Cannot query for unindexed property %s'",
"%",
"self",
".",
"_name",
")",
"from",
".",
"query",
"import",
"FilterNode",
"# Import late to avoid circular imports.",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"frozenset",
")",
")",
":",
"raise",
"datastore_errors",
".",
"BadArgumentError",
"(",
"'Expected list, tuple or set, got %r'",
"%",
"(",
"value",
",",
")",
")",
"values",
"=",
"[",
"]",
"for",
"val",
"in",
"value",
":",
"if",
"val",
"is",
"not",
"None",
":",
"val",
"=",
"self",
".",
"_do_validate",
"(",
"val",
")",
"val",
"=",
"self",
".",
"_call_to_base_type",
"(",
"val",
")",
"val",
"=",
"self",
".",
"_datastore_type",
"(",
"val",
")",
"values",
".",
"append",
"(",
"val",
")",
"return",
"FilterNode",
"(",
"self",
".",
"_name",
",",
"'in'",
",",
"values",
")"
] | 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 provided for the case you have a
StructuredProperty with a model that has a Property named IN. | [
"Comparison",
"operator",
"for",
"the",
"in",
"comparison",
"operator",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1022-L1048 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._do_validate | 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 not call all composable _validate() methods.
It only calls _validate() methods up to but not including the
first _to_base_type() method, when the MRO is traversed looking
for _validate() and _to_base_type() methods. (IOW if a class
defines both _validate() and _to_base_type(), its _validate()
is called and then the search is aborted.)
Note that for a repeated Property this function should be called
for each item in the list, not for the list as a whole.
"""
if isinstance(value, _BaseValue):
return value
value = self._call_shallow_validation(value)
if self._validator is not None:
newvalue = self._validator(self, value)
if newvalue is not None:
value = newvalue
if self._choices is not None:
if value not in self._choices:
raise datastore_errors.BadValueError(
'Value %r for property %s is not an allowed choice' %
(value, self._name))
return value | python | 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 not call all composable _validate() methods.
It only calls _validate() methods up to but not including the
first _to_base_type() method, when the MRO is traversed looking
for _validate() and _to_base_type() methods. (IOW if a class
defines both _validate() and _to_base_type(), its _validate()
is called and then the search is aborted.)
Note that for a repeated Property this function should be called
for each item in the list, not for the list as a whole.
"""
if isinstance(value, _BaseValue):
return value
value = self._call_shallow_validation(value)
if self._validator is not None:
newvalue = self._validator(self, value)
if newvalue is not None:
value = newvalue
if self._choices is not None:
if value not in self._choices:
raise datastore_errors.BadValueError(
'Value %r for property %s is not an allowed choice' %
(value, self._name))
return value | [
"def",
"_do_validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_BaseValue",
")",
":",
"return",
"value",
"value",
"=",
"self",
".",
"_call_shallow_validation",
"(",
"value",
")",
"if",
"self",
".",
"_validator",
"is",
"not",
"None",
":",
"newvalue",
"=",
"self",
".",
"_validator",
"(",
"self",
",",
"value",
")",
"if",
"newvalue",
"is",
"not",
"None",
":",
"value",
"=",
"newvalue",
"if",
"self",
".",
"_choices",
"is",
"not",
"None",
":",
"if",
"value",
"not",
"in",
"self",
".",
"_choices",
":",
"raise",
"datastore_errors",
".",
"BadValueError",
"(",
"'Value %r for property %s is not an allowed choice'",
"%",
"(",
"value",
",",
"self",
".",
"_name",
")",
")",
"return",
"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 not call all composable _validate() methods.
It only calls _validate() methods up to but not including the
first _to_base_type() method, when the MRO is traversed looking
for _validate() and _to_base_type() methods. (IOW if a class
defines both _validate() and _to_base_type(), its _validate()
is called and then the search is aborted.)
Note that for a repeated Property this function should be called
for each item in the list, not for the list as a whole. | [
"Call",
"all",
"validations",
"on",
"the",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1072-L1102 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._fix_up | 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 assigned (a.k.a. the code name). Note that this means
that each Property instance must be assigned to (at most) one
class attribute. E.g. to declare three strings, you must call
StringProperty() three times, you cannot write
foo = bar = baz = StringProperty()
"""
self._code_name = code_name
if self._name is None:
self._name = code_name | python | 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 assigned (a.k.a. the code name). Note that this means
that each Property instance must be assigned to (at most) one
class attribute. E.g. to declare three strings, you must call
StringProperty() three times, you cannot write
foo = bar = baz = StringProperty()
"""
self._code_name = code_name
if self._name is None:
self._name = code_name | [
"def",
"_fix_up",
"(",
"self",
",",
"cls",
",",
"code_name",
")",
":",
"self",
".",
"_code_name",
"=",
"code_name",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"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 assigned (a.k.a. the code name). Note that this means
that each Property instance must be assigned to (at most) one
class attribute. E.g. to declare three strings, you must call
StringProperty() three times, you cannot write
foo = bar = baz = StringProperty() | [
"Internal",
"helper",
"called",
"to",
"tell",
"the",
"property",
"its",
"name",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1104-L1119 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._set_value | 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 projection entity')
if self._repeated:
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadValueError('Expected list or tuple, got %r' %
(value,))
value = [self._do_validate(v) for v in value]
else:
if value is not None:
value = self._do_validate(value)
self._store_value(entity, value) | python | 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 projection entity')
if self._repeated:
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadValueError('Expected list or tuple, got %r' %
(value,))
value = [self._do_validate(v) for v in value]
else:
if value is not None:
value = self._do_validate(value)
self._store_value(entity, value) | [
"def",
"_set_value",
"(",
"self",
",",
"entity",
",",
"value",
")",
":",
"if",
"entity",
".",
"_projection",
":",
"raise",
"ReadonlyPropertyError",
"(",
"'You cannot set property values of a projection entity'",
")",
"if",
"self",
".",
"_repeated",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"frozenset",
")",
")",
":",
"raise",
"datastore_errors",
".",
"BadValueError",
"(",
"'Expected list or tuple, got %r'",
"%",
"(",
"value",
",",
")",
")",
"value",
"=",
"[",
"self",
".",
"_do_validate",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
"else",
":",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"_do_validate",
"(",
"value",
")",
"self",
".",
"_store_value",
"(",
"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. | [
"Internal",
"helper",
"to",
"set",
"a",
"value",
"in",
"an",
"entity",
"for",
"a",
"Property",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1129-L1146 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._retrieve_value | 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 transformations are applied.
"""
return entity._values.get(self._name, default) | python | 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 transformations are applied.
"""
return entity._values.get(self._name, default) | [
"def",
"_retrieve_value",
"(",
"self",
",",
"entity",
",",
"default",
"=",
"None",
")",
":",
"return",
"entity",
".",
"_values",
".",
"get",
"(",
"self",
".",
"_name",
",",
"default",
")"
] | 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. | [
"Internal",
"helper",
"to",
"retrieve",
"the",
"value",
"for",
"this",
"Property",
"from",
"an",
"entity",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1152-L1159 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._get_base_value_unwrapped_as_list | 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 None or
empty, returns [].
"""
wrapped = self._get_base_value(entity)
if self._repeated:
if wrapped is None:
return []
assert isinstance(wrapped, list)
return [w.b_val for w in wrapped]
else:
if wrapped is None:
return [None]
assert isinstance(wrapped, _BaseValue)
return [wrapped.b_val] | python | 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 None or
empty, returns [].
"""
wrapped = self._get_base_value(entity)
if self._repeated:
if wrapped is None:
return []
assert isinstance(wrapped, list)
return [w.b_val for w in wrapped]
else:
if wrapped is None:
return [None]
assert isinstance(wrapped, _BaseValue)
return [wrapped.b_val] | [
"def",
"_get_base_value_unwrapped_as_list",
"(",
"self",
",",
"entity",
")",
":",
"wrapped",
"=",
"self",
".",
"_get_base_value",
"(",
"entity",
")",
"if",
"self",
".",
"_repeated",
":",
"if",
"wrapped",
"is",
"None",
":",
"return",
"[",
"]",
"assert",
"isinstance",
"(",
"wrapped",
",",
"list",
")",
"return",
"[",
"w",
".",
"b_val",
"for",
"w",
"in",
"wrapped",
"]",
"else",
":",
"if",
"wrapped",
"is",
"None",
":",
"return",
"[",
"None",
"]",
"assert",
"isinstance",
"(",
"wrapped",
",",
"_BaseValue",
")",
"return",
"[",
"wrapped",
".",
"b_val",
"]"
] | 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 []. | [
"Like",
"_get_base_value",
"()",
"but",
"always",
"returns",
"a",
"list",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1183-L1202 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._opt_call_from_base_type | 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.b_val)
return value | python | 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.b_val)
return value | [
"def",
"_opt_call_from_base_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_BaseValue",
")",
":",
"value",
"=",
"self",
".",
"_call_from_base_type",
"(",
"value",
".",
"b_val",
")",
"return",
"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. | [
"Call",
"_from_base_type",
"()",
"if",
"necessary",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1204-L1213 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._opt_call_to_base_type | 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 = _BaseValue(self._call_to_base_type(value))
return value | python | 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 = _BaseValue(self._call_to_base_type(value))
return value | [
"def",
"_opt_call_to_base_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"_BaseValue",
")",
":",
"value",
"=",
"_BaseValue",
"(",
"self",
".",
"_call_to_base_type",
"(",
"value",
")",
")",
"return",
"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. | [
"Call",
"_to_base_type",
"()",
"if",
"necessary",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1226-L1235 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._call_from_base_type | 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(value) | python | 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(value) | [
"def",
"_call_from_base_type",
"(",
"self",
",",
"value",
")",
":",
"methods",
"=",
"self",
".",
"_find_methods",
"(",
"'_from_base_type'",
",",
"reverse",
"=",
"True",
")",
"call",
"=",
"self",
".",
"_apply_list",
"(",
"methods",
")",
"return",
"call",
"(",
"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. | [
"Call",
"all",
"_from_base_type",
"()",
"methods",
"on",
"the",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1237-L1245 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._call_to_base_type | 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(value) | python | 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(value) | [
"def",
"_call_to_base_type",
"(",
"self",
",",
"value",
")",
":",
"methods",
"=",
"self",
".",
"_find_methods",
"(",
"'_validate'",
",",
"'_to_base_type'",
")",
"call",
"=",
"self",
".",
"_apply_list",
"(",
"methods",
")",
"return",
"call",
"(",
"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. | [
"Call",
"all",
"_validate",
"()",
"and",
"_to_base_type",
"()",
"methods",
"on",
"the",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1247-L1255 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._call_shallow_validation | 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 ->
Property, and suppose A defines _validate() only, but B and C
define _validate() and _to_base_type(). The full list of
methods called by _call_to_base_type() is::
A._validate()
B._validate()
B._to_base_type()
C._validate()
C._to_base_type()
This method will call A._validate() and B._validate() but not the
others.
"""
methods = []
for method in self._find_methods('_validate', '_to_base_type'):
if method.__name__ != '_validate':
break
methods.append(method)
call = self._apply_list(methods)
return call(value) | python | 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 ->
Property, and suppose A defines _validate() only, but B and C
define _validate() and _to_base_type(). The full list of
methods called by _call_to_base_type() is::
A._validate()
B._validate()
B._to_base_type()
C._validate()
C._to_base_type()
This method will call A._validate() and B._validate() but not the
others.
"""
methods = []
for method in self._find_methods('_validate', '_to_base_type'):
if method.__name__ != '_validate':
break
methods.append(method)
call = self._apply_list(methods)
return call(value) | [
"def",
"_call_shallow_validation",
"(",
"self",
",",
"value",
")",
":",
"methods",
"=",
"[",
"]",
"for",
"method",
"in",
"self",
".",
"_find_methods",
"(",
"'_validate'",
",",
"'_to_base_type'",
")",
":",
"if",
"method",
".",
"__name__",
"!=",
"'_validate'",
":",
"break",
"methods",
".",
"append",
"(",
"method",
")",
"call",
"=",
"self",
".",
"_apply_list",
"(",
"methods",
")",
"return",
"call",
"(",
"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 ->
Property, and suppose A defines _validate() only, but B and C
define _validate() and _to_base_type(). The full list of
methods called by _call_to_base_type() is::
A._validate()
B._validate()
B._to_base_type()
C._validate()
C._to_base_type()
This method will call A._validate() and B._validate() but not the
others. | [
"Call",
"the",
"initial",
"set",
"of",
"_validate",
"()",
"methods",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1257-L1284 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._find_methods | 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 or more method names.
reverse: Optional flag, default False; if True, the list is
reversed.
Returns:
A list of callable class method objects.
"""
reverse = kwds.pop('reverse', False)
assert not kwds, repr(kwds)
cache = cls.__dict__.get('_find_methods_cache')
if cache:
hit = cache.get(names)
if hit is not None:
return hit
else:
cls._find_methods_cache = cache = {}
methods = []
for c in cls.__mro__:
for name in names:
method = c.__dict__.get(name)
if method is not None:
methods.append(method)
if reverse:
methods.reverse()
cache[names] = methods
return methods | python | 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 or more method names.
reverse: Optional flag, default False; if True, the list is
reversed.
Returns:
A list of callable class method objects.
"""
reverse = kwds.pop('reverse', False)
assert not kwds, repr(kwds)
cache = cls.__dict__.get('_find_methods_cache')
if cache:
hit = cache.get(names)
if hit is not None:
return hit
else:
cls._find_methods_cache = cache = {}
methods = []
for c in cls.__mro__:
for name in names:
method = c.__dict__.get(name)
if method is not None:
methods.append(method)
if reverse:
methods.reverse()
cache[names] = methods
return methods | [
"def",
"_find_methods",
"(",
"cls",
",",
"*",
"names",
",",
"*",
"*",
"kwds",
")",
":",
"reverse",
"=",
"kwds",
".",
"pop",
"(",
"'reverse'",
",",
"False",
")",
"assert",
"not",
"kwds",
",",
"repr",
"(",
"kwds",
")",
"cache",
"=",
"cls",
".",
"__dict__",
".",
"get",
"(",
"'_find_methods_cache'",
")",
"if",
"cache",
":",
"hit",
"=",
"cache",
".",
"get",
"(",
"names",
")",
"if",
"hit",
"is",
"not",
"None",
":",
"return",
"hit",
"else",
":",
"cls",
".",
"_find_methods_cache",
"=",
"cache",
"=",
"{",
"}",
"methods",
"=",
"[",
"]",
"for",
"c",
"in",
"cls",
".",
"__mro__",
":",
"for",
"name",
"in",
"names",
":",
"method",
"=",
"c",
".",
"__dict__",
".",
"get",
"(",
"name",
")",
"if",
"method",
"is",
"not",
"None",
":",
"methods",
".",
"append",
"(",
"method",
")",
"if",
"reverse",
":",
"methods",
".",
"reverse",
"(",
")",
"cache",
"[",
"names",
"]",
"=",
"methods",
"return",
"methods"
] | 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 flag, default False; if True, the list is
reversed.
Returns:
A list of callable class method objects. | [
"Compute",
"a",
"list",
"of",
"composable",
"methods",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1287-L1320 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._apply_list | 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:
newvalue = method(self, value)
if newvalue is not None:
value = newvalue
return value
return call | python | 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:
newvalue = method(self, value)
if newvalue is not None:
value = newvalue
return value
return call | [
"def",
"_apply_list",
"(",
"self",
",",
"methods",
")",
":",
"def",
"call",
"(",
"value",
")",
":",
"for",
"method",
"in",
"methods",
":",
"newvalue",
"=",
"method",
"(",
"self",
",",
"value",
")",
"if",
"newvalue",
"is",
"not",
"None",
":",
"value",
"=",
"newvalue",
"return",
"value",
"return",
"call"
] | 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. | [
"Return",
"a",
"single",
"callable",
"that",
"applies",
"a",
"list",
"of",
"methods",
"to",
"a",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1322-L1335 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._apply_to_values | 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
resulting value or list of values is both stored back in the
entity and returned from this method.
"""
value = self._retrieve_value(entity, self._default)
if self._repeated:
if value is None:
value = []
self._store_value(entity, value)
else:
value[:] = map(function, value)
else:
if value is not None:
newvalue = function(value)
if newvalue is not None and newvalue is not value:
self._store_value(entity, newvalue)
value = newvalue
return value | python | 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
resulting value or list of values is both stored back in the
entity and returned from this method.
"""
value = self._retrieve_value(entity, self._default)
if self._repeated:
if value is None:
value = []
self._store_value(entity, value)
else:
value[:] = map(function, value)
else:
if value is not None:
newvalue = function(value)
if newvalue is not None and newvalue is not value:
self._store_value(entity, newvalue)
value = newvalue
return value | [
"def",
"_apply_to_values",
"(",
"self",
",",
"entity",
",",
"function",
")",
":",
"value",
"=",
"self",
".",
"_retrieve_value",
"(",
"entity",
",",
"self",
".",
"_default",
")",
"if",
"self",
".",
"_repeated",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"[",
"]",
"self",
".",
"_store_value",
"(",
"entity",
",",
"value",
")",
"else",
":",
"value",
"[",
":",
"]",
"=",
"map",
"(",
"function",
",",
"value",
")",
"else",
":",
"if",
"value",
"is",
"not",
"None",
":",
"newvalue",
"=",
"function",
"(",
"value",
")",
"if",
"newvalue",
"is",
"not",
"None",
"and",
"newvalue",
"is",
"not",
"value",
":",
"self",
".",
"_store_value",
"(",
"entity",
",",
"newvalue",
")",
"value",
"=",
"newvalue",
"return",
"value"
] | 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 back in the
entity and returned from this method. | [
"Apply",
"a",
"function",
"to",
"the",
"property",
"value",
"/",
"values",
"of",
"a",
"given",
"entity",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1337-L1359 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._get_value | 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(
'Property %s is not in the projection' % (self._name,))
return self._get_user_value(entity) | python | 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(
'Property %s is not in the projection' % (self._name,))
return self._get_user_value(entity) | [
"def",
"_get_value",
"(",
"self",
",",
"entity",
")",
":",
"if",
"entity",
".",
"_projection",
":",
"if",
"self",
".",
"_name",
"not",
"in",
"entity",
".",
"_projection",
":",
"raise",
"UnprojectedPropertyError",
"(",
"'Property %s is not in the projection'",
"%",
"(",
"self",
".",
"_name",
",",
")",
")",
"return",
"self",
".",
"_get_user_value",
"(",
"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. | [
"Internal",
"helper",
"to",
"get",
"the",
"value",
"for",
"this",
"Property",
"from",
"an",
"entity",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1361-L1371 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._delete_value | 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 self._name in entity._values:
del entity._values[self._name] | python | 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 self._name in entity._values:
del entity._values[self._name] | [
"def",
"_delete_value",
"(",
"self",
",",
"entity",
")",
":",
"if",
"self",
".",
"_name",
"in",
"entity",
".",
"_values",
":",
"del",
"entity",
".",
"_values",
"[",
"self",
".",
"_name",
"]"
] | 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). | [
"Internal",
"helper",
"to",
"delete",
"the",
"value",
"for",
"this",
"Property",
"from",
"an",
"entity",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1373-L1381 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._is_initialized | 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) is not None)) | python | 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) is not None)) | [
"def",
"_is_initialized",
"(",
"self",
",",
"entity",
")",
":",
"return",
"(",
"not",
"self",
".",
"_required",
"or",
"(",
"(",
"self",
".",
"_has_value",
"(",
"entity",
")",
"or",
"self",
".",
"_default",
"is",
"not",
"None",
")",
"and",
"self",
".",
"_get_value",
"(",
"entity",
")",
"is",
"not",
"None",
")",
")"
] | 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. | [
"Internal",
"helper",
"to",
"ask",
"if",
"the",
"entity",
"has",
"a",
"value",
"for",
"this",
"Property",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1383-L1390 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._serialize | 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 EntityProto instance.
prefix: Optional name prefix used for StructuredProperty
(if present, must end in '.').
parent_repeated: True if the parent (or an earlier ancestor)
is a repeated Property.
projection: A list or tuple of strings representing the projection for
the model instance, or None if the instance is not a projection.
"""
values = self._get_base_value_unwrapped_as_list(entity)
name = prefix + self._name
if projection and name not in projection:
return
if self._indexed:
create_prop = lambda: pb.add_property()
else:
create_prop = lambda: pb.add_raw_property()
if self._repeated and not values and self._write_empty_list:
# We want to write the empty list
p = create_prop()
p.set_name(name)
p.set_multiple(False)
p.set_meaning(entity_pb.Property.EMPTY_LIST)
p.mutable_value()
else:
# We write a list, or a single property
for val in values:
p = create_prop()
p.set_name(name)
p.set_multiple(self._repeated or parent_repeated)
v = p.mutable_value()
if val is not None:
self._db_set_value(v, p, val)
if projection:
# Projected properties have the INDEX_VALUE meaning and only contain
# the original property's name and value.
new_p = entity_pb.Property()
new_p.set_name(p.name())
new_p.set_meaning(entity_pb.Property.INDEX_VALUE)
new_p.set_multiple(False)
new_p.mutable_value().CopyFrom(v)
p.CopyFrom(new_p) | python | 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 EntityProto instance.
prefix: Optional name prefix used for StructuredProperty
(if present, must end in '.').
parent_repeated: True if the parent (or an earlier ancestor)
is a repeated Property.
projection: A list or tuple of strings representing the projection for
the model instance, or None if the instance is not a projection.
"""
values = self._get_base_value_unwrapped_as_list(entity)
name = prefix + self._name
if projection and name not in projection:
return
if self._indexed:
create_prop = lambda: pb.add_property()
else:
create_prop = lambda: pb.add_raw_property()
if self._repeated and not values and self._write_empty_list:
# We want to write the empty list
p = create_prop()
p.set_name(name)
p.set_multiple(False)
p.set_meaning(entity_pb.Property.EMPTY_LIST)
p.mutable_value()
else:
# We write a list, or a single property
for val in values:
p = create_prop()
p.set_name(name)
p.set_multiple(self._repeated or parent_repeated)
v = p.mutable_value()
if val is not None:
self._db_set_value(v, p, val)
if projection:
# Projected properties have the INDEX_VALUE meaning and only contain
# the original property's name and value.
new_p = entity_pb.Property()
new_p.set_name(p.name())
new_p.set_meaning(entity_pb.Property.INDEX_VALUE)
new_p.set_multiple(False)
new_p.mutable_value().CopyFrom(v)
p.CopyFrom(new_p) | [
"def",
"_serialize",
"(",
"self",
",",
"entity",
",",
"pb",
",",
"prefix",
"=",
"''",
",",
"parent_repeated",
"=",
"False",
",",
"projection",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"_get_base_value_unwrapped_as_list",
"(",
"entity",
")",
"name",
"=",
"prefix",
"+",
"self",
".",
"_name",
"if",
"projection",
"and",
"name",
"not",
"in",
"projection",
":",
"return",
"if",
"self",
".",
"_indexed",
":",
"create_prop",
"=",
"lambda",
":",
"pb",
".",
"add_property",
"(",
")",
"else",
":",
"create_prop",
"=",
"lambda",
":",
"pb",
".",
"add_raw_property",
"(",
")",
"if",
"self",
".",
"_repeated",
"and",
"not",
"values",
"and",
"self",
".",
"_write_empty_list",
":",
"# We want to write the empty list",
"p",
"=",
"create_prop",
"(",
")",
"p",
".",
"set_name",
"(",
"name",
")",
"p",
".",
"set_multiple",
"(",
"False",
")",
"p",
".",
"set_meaning",
"(",
"entity_pb",
".",
"Property",
".",
"EMPTY_LIST",
")",
"p",
".",
"mutable_value",
"(",
")",
"else",
":",
"# We write a list, or a single property",
"for",
"val",
"in",
"values",
":",
"p",
"=",
"create_prop",
"(",
")",
"p",
".",
"set_name",
"(",
"name",
")",
"p",
".",
"set_multiple",
"(",
"self",
".",
"_repeated",
"or",
"parent_repeated",
")",
"v",
"=",
"p",
".",
"mutable_value",
"(",
")",
"if",
"val",
"is",
"not",
"None",
":",
"self",
".",
"_db_set_value",
"(",
"v",
",",
"p",
",",
"val",
")",
"if",
"projection",
":",
"# Projected properties have the INDEX_VALUE meaning and only contain",
"# the original property's name and value.",
"new_p",
"=",
"entity_pb",
".",
"Property",
"(",
")",
"new_p",
".",
"set_name",
"(",
"p",
".",
"name",
"(",
")",
")",
"new_p",
".",
"set_meaning",
"(",
"entity_pb",
".",
"Property",
".",
"INDEX_VALUE",
")",
"new_p",
".",
"set_multiple",
"(",
"False",
")",
"new_p",
".",
"mutable_value",
"(",
")",
".",
"CopyFrom",
"(",
"v",
")",
"p",
".",
"CopyFrom",
"(",
"new_p",
")"
] | 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 end in '.').
parent_repeated: True if the parent (or an earlier ancestor)
is a repeated Property.
projection: A list or tuple of strings representing the projection for
the model instance, or None if the instance is not a projection. | [
"Internal",
"helper",
"to",
"serialize",
"this",
"property",
"to",
"a",
"protocol",
"buffer",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1406-L1456 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._deserialize | 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 depth, default 1 (unused here, but used
by some subclasses that override this method).
"""
if p.meaning() == entity_pb.Property.EMPTY_LIST:
self._store_value(entity, [])
return
val = self._db_get_value(p.value(), p)
if val is not None:
val = _BaseValue(val)
# TODO: replace the remainder of the function with the following commented
# out code once its feasible to make breaking changes such as not calling
# _store_value().
# if self._repeated:
# entity._values.setdefault(self._name, []).append(val)
# else:
# entity._values[self._name] = val
if self._repeated:
if self._has_value(entity):
value = self._retrieve_value(entity)
assert isinstance(value, list), repr(value)
value.append(val)
else:
# We promote single values to lists if we are a list property
value = [val]
else:
value = val
self._store_value(entity, value) | python | 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 depth, default 1 (unused here, but used
by some subclasses that override this method).
"""
if p.meaning() == entity_pb.Property.EMPTY_LIST:
self._store_value(entity, [])
return
val = self._db_get_value(p.value(), p)
if val is not None:
val = _BaseValue(val)
# TODO: replace the remainder of the function with the following commented
# out code once its feasible to make breaking changes such as not calling
# _store_value().
# if self._repeated:
# entity._values.setdefault(self._name, []).append(val)
# else:
# entity._values[self._name] = val
if self._repeated:
if self._has_value(entity):
value = self._retrieve_value(entity)
assert isinstance(value, list), repr(value)
value.append(val)
else:
# We promote single values to lists if we are a list property
value = [val]
else:
value = val
self._store_value(entity, value) | [
"def",
"_deserialize",
"(",
"self",
",",
"entity",
",",
"p",
",",
"unused_depth",
"=",
"1",
")",
":",
"if",
"p",
".",
"meaning",
"(",
")",
"==",
"entity_pb",
".",
"Property",
".",
"EMPTY_LIST",
":",
"self",
".",
"_store_value",
"(",
"entity",
",",
"[",
"]",
")",
"return",
"val",
"=",
"self",
".",
"_db_get_value",
"(",
"p",
".",
"value",
"(",
")",
",",
"p",
")",
"if",
"val",
"is",
"not",
"None",
":",
"val",
"=",
"_BaseValue",
"(",
"val",
")",
"# TODO: replace the remainder of the function with the following commented",
"# out code once its feasible to make breaking changes such as not calling",
"# _store_value().",
"# if self._repeated:",
"# entity._values.setdefault(self._name, []).append(val)",
"# else:",
"# entity._values[self._name] = val",
"if",
"self",
".",
"_repeated",
":",
"if",
"self",
".",
"_has_value",
"(",
"entity",
")",
":",
"value",
"=",
"self",
".",
"_retrieve_value",
"(",
"entity",
")",
"assert",
"isinstance",
"(",
"value",
",",
"list",
")",
",",
"repr",
"(",
"value",
")",
"value",
".",
"append",
"(",
"val",
")",
"else",
":",
"# We promote single values to lists if we are a list property",
"value",
"=",
"[",
"val",
"]",
"else",
":",
"value",
"=",
"val",
"self",
".",
"_store_value",
"(",
"entity",
",",
"value",
")"
] | 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 subclasses that override this method). | [
"Internal",
"helper",
"to",
"deserialize",
"this",
"property",
"from",
"a",
"protocol",
"buffer",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1458-L1496 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Property._check_property | 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 does not meet the given
requirements or if a subproperty is specified. (StructuredProperty
overrides this method to handle subproperties.)
"""
if require_indexed and not self._indexed:
raise InvalidPropertyError('Property is unindexed %s' % self._name)
if rest:
raise InvalidPropertyError('Referencing subproperty %s.%s '
'but %s is not a structured property' %
(self._name, rest, self._name)) | python | 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 does not meet the given
requirements or if a subproperty is specified. (StructuredProperty
overrides this method to handle subproperties.)
"""
if require_indexed and not self._indexed:
raise InvalidPropertyError('Property is unindexed %s' % self._name)
if rest:
raise InvalidPropertyError('Referencing subproperty %s.%s '
'but %s is not a structured property' %
(self._name, rest, self._name)) | [
"def",
"_check_property",
"(",
"self",
",",
"rest",
"=",
"None",
",",
"require_indexed",
"=",
"True",
")",
":",
"if",
"require_indexed",
"and",
"not",
"self",
".",
"_indexed",
":",
"raise",
"InvalidPropertyError",
"(",
"'Property is unindexed %s'",
"%",
"self",
".",
"_name",
")",
"if",
"rest",
":",
"raise",
"InvalidPropertyError",
"(",
"'Referencing subproperty %s.%s '",
"'but %s is not a structured property'",
"%",
"(",
"self",
".",
"_name",
",",
"rest",
",",
"self",
".",
"_name",
")",
")"
] | 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 specified. (StructuredProperty
overrides this method to handle subproperties.) | [
"Internal",
"helper",
"to",
"check",
"this",
"property",
"for",
"specific",
"requirements",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1501-L1519 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | ModelKey._set_value | 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 | python | 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",
"_set_value",
"(",
"self",
",",
"entity",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"_validate_key",
"(",
"value",
",",
"entity",
"=",
"entity",
")",
"value",
"=",
"entity",
".",
"_validate_key",
"(",
"value",
")",
"entity",
".",
"_entity_key",
"=",
"value"
] | Setter for key attribute. | [
"Setter",
"for",
"key",
"attribute",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L1573-L1578 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | StructuredProperty._get_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)
return value | python | 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)
return value | [
"def",
"_get_value",
"(",
"self",
",",
"entity",
")",
":",
"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",
")",
"return",
"value"
] | Override _get_value() to *not* raise UnprojectedPropertyError. | [
"Override",
"_get_value",
"()",
"to",
"*",
"not",
"*",
"raise",
"UnprojectedPropertyError",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2262-L2268 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | StructuredProperty._check_property | 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 property %s requires a subproperty' % self._name)
self._modelclass._check_properties([rest], require_indexed=require_indexed) | python | 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 property %s requires a subproperty' % self._name)
self._modelclass._check_properties([rest], require_indexed=require_indexed) | [
"def",
"_check_property",
"(",
"self",
",",
"rest",
"=",
"None",
",",
"require_indexed",
"=",
"True",
")",
":",
"if",
"not",
"rest",
":",
"raise",
"InvalidPropertyError",
"(",
"'Structured property %s requires a subproperty'",
"%",
"self",
".",
"_name",
")",
"self",
".",
"_modelclass",
".",
"_check_properties",
"(",
"[",
"rest",
"]",
",",
"require_indexed",
"=",
"require_indexed",
")"
] | Override for Property._check_property().
Raises:
InvalidPropertyError if no subproperty is specified or if something
is wrong with the subproperty. | [
"Override",
"for",
"Property",
".",
"_check_property",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2508-L2518 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model.__get_arg | 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):
return kwds.pop(kwd)
return None | python | 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):
return kwds.pop(kwd)
return None | [
"def",
"__get_arg",
"(",
"cls",
",",
"kwds",
",",
"kwd",
")",
":",
"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",
")",
":",
"return",
"kwds",
".",
"pop",
"(",
"kwd",
")",
"return",
"None"
] | Internal helper method to parse keywords that may be property names. | [
"Internal",
"helper",
"method",
"to",
"parse",
"keywords",
"that",
"may",
"be",
"property",
"names",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2953-L2962 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._set_attributes | 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):
raise TypeError('Cannot set non-property %s' % name)
prop._set_value(self, value) | python | 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):
raise TypeError('Cannot set non-property %s' % name)
prop._set_value(self, value) | [
"def",
"_set_attributes",
"(",
"self",
",",
"kwds",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"for",
"name",
",",
"value",
"in",
"kwds",
".",
"iteritems",
"(",
")",
":",
"prop",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"# Raises AttributeError for unknown properties.",
"if",
"not",
"isinstance",
"(",
"prop",
",",
"Property",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot set non-property %s'",
"%",
"name",
")",
"prop",
".",
"_set_value",
"(",
"self",
",",
"value",
")"
] | Internal helper to set attributes from keyword arguments.
Expando overrides this. | [
"Internal",
"helper",
"to",
"set",
"attributes",
"from",
"keyword",
"arguments",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2983-L2993 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._find_uninitialized | 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)) | python | 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",
"_find_uninitialized",
"(",
"self",
")",
":",
"return",
"set",
"(",
"name",
"for",
"name",
",",
"prop",
"in",
"self",
".",
"_properties",
".",
"iteritems",
"(",
")",
"if",
"not",
"prop",
".",
"_is_initialized",
"(",
"self",
")",
")"
] | Internal helper to find uninitialized properties.
Returns:
A set of property names. | [
"Internal",
"helper",
"to",
"find",
"uninitialized",
"properties",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L2995-L3003 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._check_initialized | 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(baddies)) | python | 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(baddies)) | [
"def",
"_check_initialized",
"(",
"self",
")",
":",
"baddies",
"=",
"self",
".",
"_find_uninitialized",
"(",
")",
"if",
"baddies",
":",
"raise",
"datastore_errors",
".",
"BadValueError",
"(",
"'Entity has uninitialized properties: %s'",
"%",
"', '",
".",
"join",
"(",
"baddies",
")",
")"
] | Internal helper to check for uninitialized properties.
Raises:
BadValueError if it finds any. | [
"Internal",
"helper",
"to",
"check",
"for",
"uninitialized",
"properties",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3005-L3014 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._reset_kind_map | 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.update(keep) | python | 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.update(keep) | [
"def",
"_reset_kind_map",
"(",
"cls",
")",
":",
"# 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",
".",
"update",
"(",
"keep",
")"
] | Clear the kind map. Useful for testing. | [
"Clear",
"the",
"kind",
"map",
".",
"Useful",
"for",
"testing",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3074-L3082 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._lookup_model | 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:
KindError: The kind was not found and no default_model was provided.
"""
modelclass = cls._kind_map.get(kind, default_model)
if modelclass is None:
raise KindError(
"No model class found for kind '%s'. Did you forget to import it?" %
kind)
return modelclass | python | 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:
KindError: The kind was not found and no default_model was provided.
"""
modelclass = cls._kind_map.get(kind, default_model)
if modelclass is None:
raise KindError(
"No model class found for kind '%s'. Did you forget to import it?" %
kind)
return modelclass | [
"def",
"_lookup_model",
"(",
"cls",
",",
"kind",
",",
"default_model",
"=",
"None",
")",
":",
"modelclass",
"=",
"cls",
".",
"_kind_map",
".",
"get",
"(",
"kind",
",",
"default_model",
")",
"if",
"modelclass",
"is",
"None",
":",
"raise",
"KindError",
"(",
"\"No model class found for kind '%s'. Did you forget to import it?\"",
"%",
"kind",
")",
"return",
"modelclass"
] | 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 provided. | [
"Get",
"the",
"model",
"class",
"for",
"the",
"kind",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3085-L3102 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._equivalent | 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__,
other.__class_.__name__))
if set(self._projection) != set(other._projection):
return False
# It's all about determining inequality early.
if len(self._properties) != len(other._properties):
return False # Can only happen for Expandos.
my_prop_names = set(self._properties.iterkeys())
their_prop_names = set(other._properties.iterkeys())
if my_prop_names != their_prop_names:
return False # Again, only possible for Expandos.
if self._projection:
my_prop_names = set(self._projection)
for name in my_prop_names:
if '.' in name:
name, _ = name.split('.', 1)
my_value = self._properties[name]._get_value(self)
their_value = other._properties[name]._get_value(other)
if my_value != their_value:
return False
return True | python | 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__,
other.__class_.__name__))
if set(self._projection) != set(other._projection):
return False
# It's all about determining inequality early.
if len(self._properties) != len(other._properties):
return False # Can only happen for Expandos.
my_prop_names = set(self._properties.iterkeys())
their_prop_names = set(other._properties.iterkeys())
if my_prop_names != their_prop_names:
return False # Again, only possible for Expandos.
if self._projection:
my_prop_names = set(self._projection)
for name in my_prop_names:
if '.' in name:
name, _ = name.split('.', 1)
my_value = self._properties[name]._get_value(self)
their_value = other._properties[name]._get_value(other)
if my_value != their_value:
return False
return True | [
"def",
"_equivalent",
"(",
"self",
",",
"other",
")",
":",
"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__",
",",
"other",
".",
"__class_",
".",
"__name__",
")",
")",
"if",
"set",
"(",
"self",
".",
"_projection",
")",
"!=",
"set",
"(",
"other",
".",
"_projection",
")",
":",
"return",
"False",
"# It's all about determining inequality early.",
"if",
"len",
"(",
"self",
".",
"_properties",
")",
"!=",
"len",
"(",
"other",
".",
"_properties",
")",
":",
"return",
"False",
"# Can only happen for Expandos.",
"my_prop_names",
"=",
"set",
"(",
"self",
".",
"_properties",
".",
"iterkeys",
"(",
")",
")",
"their_prop_names",
"=",
"set",
"(",
"other",
".",
"_properties",
".",
"iterkeys",
"(",
")",
")",
"if",
"my_prop_names",
"!=",
"their_prop_names",
":",
"return",
"False",
"# Again, only possible for Expandos.",
"if",
"self",
".",
"_projection",
":",
"my_prop_names",
"=",
"set",
"(",
"self",
".",
"_projection",
")",
"for",
"name",
"in",
"my_prop_names",
":",
"if",
"'.'",
"in",
"name",
":",
"name",
",",
"_",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"my_value",
"=",
"self",
".",
"_properties",
"[",
"name",
"]",
".",
"_get_value",
"(",
"self",
")",
"their_value",
"=",
"other",
".",
"_properties",
"[",
"name",
"]",
".",
"_get_value",
"(",
"other",
")",
"if",
"my_value",
"!=",
"their_value",
":",
"return",
"False",
"return",
"True"
] | Compare two entities of the same class, excluding keys. | [
"Compare",
"two",
"entities",
"of",
"the",
"same",
"class",
"excluding",
"keys",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3129-L3153 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._to_pb | 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.entity_to_pb()?
self._key_to_pb(pb)
for unused_name, prop in sorted(self._properties.iteritems()):
prop._serialize(self, pb, projection=self._projection)
return pb | python | 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.entity_to_pb()?
self._key_to_pb(pb)
for unused_name, prop in sorted(self._properties.iteritems()):
prop._serialize(self, pb, projection=self._projection)
return pb | [
"def",
"_to_pb",
"(",
"self",
",",
"pb",
"=",
"None",
",",
"allow_partial",
"=",
"False",
",",
"set_key",
"=",
"True",
")",
":",
"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.entity_to_pb()?",
"self",
".",
"_key_to_pb",
"(",
"pb",
")",
"for",
"unused_name",
",",
"prop",
"in",
"sorted",
"(",
"self",
".",
"_properties",
".",
"iteritems",
"(",
")",
")",
":",
"prop",
".",
"_serialize",
"(",
"self",
",",
"pb",
",",
"projection",
"=",
"self",
".",
"_projection",
")",
"return",
"pb"
] | Internal helper to turn an entity into an EntityProto protobuf. | [
"Internal",
"helper",
"to",
"turn",
"an",
"entity",
"into",
"an",
"EntityProto",
"protobuf",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3155-L3169 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._key_to_pb | 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)
group = pb.mutable_entity_group() # Must initialize this.
# To work around an SDK issue, only set the entity group if the
# full key is complete. TODO: Remove the top test once fixed.
if key is not None and key.id():
elem = ref.path().element(0)
if elem.id() or elem.name():
group.add_element().CopyFrom(elem) | python | 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)
group = pb.mutable_entity_group() # Must initialize this.
# To work around an SDK issue, only set the entity group if the
# full key is complete. TODO: Remove the top test once fixed.
if key is not None and key.id():
elem = ref.path().element(0)
if elem.id() or elem.name():
group.add_element().CopyFrom(elem) | [
"def",
"_key_to_pb",
"(",
"self",
",",
"pb",
")",
":",
"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",
")",
"group",
"=",
"pb",
".",
"mutable_entity_group",
"(",
")",
"# Must initialize this.",
"# To work around an SDK issue, only set the entity group if the",
"# full key is complete. TODO: Remove the top test once fixed.",
"if",
"key",
"is",
"not",
"None",
"and",
"key",
".",
"id",
"(",
")",
":",
"elem",
"=",
"ref",
".",
"path",
"(",
")",
".",
"element",
"(",
"0",
")",
"if",
"elem",
".",
"id",
"(",
")",
"or",
"elem",
".",
"name",
"(",
")",
":",
"group",
".",
"add_element",
"(",
")",
".",
"CopyFrom",
"(",
"elem",
")"
] | Internal helper to copy the key into a protobuf. | [
"Internal",
"helper",
"to",
"copy",
"the",
"key",
"into",
"a",
"protobuf",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3171-L3186 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._from_pb | 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 overrides a key in the pb.
if key is None and pb.key().path().element_size():
key = Key(reference=pb.key())
# If set_key is not set, skip a trivial incomplete key.
if key is not None and (set_key or key.id() or key.parent()):
ent._key = key
# NOTE(darke): Keep a map from (indexed, property name) to the property.
# This allows us to skip the (relatively) expensive call to
# _get_property_for for repeated fields.
_property_map = {}
projection = []
for indexed, plist in ((True, pb.property_list()),
(False, pb.raw_property_list())):
for p in plist:
if p.meaning() == entity_pb.Property.INDEX_VALUE:
projection.append(p.name())
property_map_key = (p.name(), indexed)
if property_map_key not in _property_map:
_property_map[property_map_key] = ent._get_property_for(p, indexed)
_property_map[property_map_key]._deserialize(ent, p)
ent._set_projection(projection)
return ent | python | 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 overrides a key in the pb.
if key is None and pb.key().path().element_size():
key = Key(reference=pb.key())
# If set_key is not set, skip a trivial incomplete key.
if key is not None and (set_key or key.id() or key.parent()):
ent._key = key
# NOTE(darke): Keep a map from (indexed, property name) to the property.
# This allows us to skip the (relatively) expensive call to
# _get_property_for for repeated fields.
_property_map = {}
projection = []
for indexed, plist in ((True, pb.property_list()),
(False, pb.raw_property_list())):
for p in plist:
if p.meaning() == entity_pb.Property.INDEX_VALUE:
projection.append(p.name())
property_map_key = (p.name(), indexed)
if property_map_key not in _property_map:
_property_map[property_map_key] = ent._get_property_for(p, indexed)
_property_map[property_map_key]._deserialize(ent, p)
ent._set_projection(projection)
return ent | [
"def",
"_from_pb",
"(",
"cls",
",",
"pb",
",",
"set_key",
"=",
"True",
",",
"ent",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"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 overrides a key in the pb.",
"if",
"key",
"is",
"None",
"and",
"pb",
".",
"key",
"(",
")",
".",
"path",
"(",
")",
".",
"element_size",
"(",
")",
":",
"key",
"=",
"Key",
"(",
"reference",
"=",
"pb",
".",
"key",
"(",
")",
")",
"# If set_key is not set, skip a trivial incomplete key.",
"if",
"key",
"is",
"not",
"None",
"and",
"(",
"set_key",
"or",
"key",
".",
"id",
"(",
")",
"or",
"key",
".",
"parent",
"(",
")",
")",
":",
"ent",
".",
"_key",
"=",
"key",
"# NOTE(darke): Keep a map from (indexed, property name) to the property.",
"# This allows us to skip the (relatively) expensive call to",
"# _get_property_for for repeated fields.",
"_property_map",
"=",
"{",
"}",
"projection",
"=",
"[",
"]",
"for",
"indexed",
",",
"plist",
"in",
"(",
"(",
"True",
",",
"pb",
".",
"property_list",
"(",
")",
")",
",",
"(",
"False",
",",
"pb",
".",
"raw_property_list",
"(",
")",
")",
")",
":",
"for",
"p",
"in",
"plist",
":",
"if",
"p",
".",
"meaning",
"(",
")",
"==",
"entity_pb",
".",
"Property",
".",
"INDEX_VALUE",
":",
"projection",
".",
"append",
"(",
"p",
".",
"name",
"(",
")",
")",
"property_map_key",
"=",
"(",
"p",
".",
"name",
"(",
")",
",",
"indexed",
")",
"if",
"property_map_key",
"not",
"in",
"_property_map",
":",
"_property_map",
"[",
"property_map_key",
"]",
"=",
"ent",
".",
"_get_property_for",
"(",
"p",
",",
"indexed",
")",
"_property_map",
"[",
"property_map_key",
"]",
".",
"_deserialize",
"(",
"ent",
",",
"p",
")",
"ent",
".",
"_set_projection",
"(",
"projection",
")",
"return",
"ent"
] | Internal helper to create an entity from an EntityProto protobuf. | [
"Internal",
"helper",
"to",
"create",
"an",
"entity",
"from",
"an",
"EntityProto",
"protobuf",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3189-L3219 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._get_property_for | 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 could also be that a schema change turned an unstructured
# value into a structured one. In that case, too, it seems
# better to return None than to return an unstructured value,
# since the latter doesn't match the current schema.)
return None
next = parts[depth]
prop = self._properties.get(next)
if prop is None:
prop = self._fake_property(p, next, indexed)
return prop | python | 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 could also be that a schema change turned an unstructured
# value into a structured one. In that case, too, it seems
# better to return None than to return an unstructured value,
# since the latter doesn't match the current schema.)
return None
next = parts[depth]
prop = self._properties.get(next)
if prop is None:
prop = self._fake_property(p, next, indexed)
return prop | [
"def",
"_get_property_for",
"(",
"self",
",",
"p",
",",
"indexed",
"=",
"True",
",",
"depth",
"=",
"0",
")",
":",
"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 could also be that a schema change turned an unstructured",
"# value into a structured one. In that case, too, it seems",
"# better to return None than to return an unstructured value,",
"# since the latter doesn't match the current schema.)",
"return",
"None",
"next",
"=",
"parts",
"[",
"depth",
"]",
"prop",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"next",
")",
"if",
"prop",
"is",
"None",
":",
"prop",
"=",
"self",
".",
"_fake_property",
"(",
"p",
",",
"next",
",",
"indexed",
")",
"return",
"prop"
] | Internal helper to get the Property for a protobuf-level property. | [
"Internal",
"helper",
"to",
"get",
"the",
"Property",
"for",
"a",
"protobuf",
"-",
"level",
"property",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3238-L3253 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._clone_properties | 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) | python | 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",
"_clone_properties",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"self",
".",
"_properties",
"is",
"cls",
".",
"_properties",
":",
"self",
".",
"_properties",
"=",
"dict",
"(",
"cls",
".",
"_properties",
")"
] | Internal helper to clone self._properties if necessary. | [
"Internal",
"helper",
"to",
"clone",
"self",
".",
"_properties",
"if",
"necessary",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3255-L3259 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._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, _BaseValue(Expando()))
else:
compressed = p.meaning_uri() == _MEANING_URI_COMPRESSED
prop = GenericProperty(next,
repeated=p.multiple(),
indexed=indexed,
compressed=compressed)
prop._code_name = next
self._properties[prop._name] = prop
return prop | python | 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 = p.meaning_uri() == _MEANING_URI_COMPRESSED
prop = GenericProperty(next,
repeated=p.multiple(),
indexed=indexed,
compressed=compressed)
prop._code_name = next
self._properties[prop._name] = prop
return prop | [
"def",
"_fake_property",
"(",
"self",
",",
"p",
",",
"next",
",",
"indexed",
"=",
"True",
")",
":",
"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",
"=",
"p",
".",
"meaning_uri",
"(",
")",
"==",
"_MEANING_URI_COMPRESSED",
"prop",
"=",
"GenericProperty",
"(",
"next",
",",
"repeated",
"=",
"p",
".",
"multiple",
"(",
")",
",",
"indexed",
"=",
"indexed",
",",
"compressed",
"=",
"compressed",
")",
"prop",
".",
"_code_name",
"=",
"next",
"self",
".",
"_properties",
"[",
"prop",
".",
"_name",
"]",
"=",
"prop",
"return",
"prop"
] | Internal helper to create a fake Property. | [
"Internal",
"helper",
"to",
"create",
"a",
"fake",
"Property",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3261-L3275 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._to_dict | 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 excluded.
"""
if (include is not None and
not isinstance(include, (list, tuple, set, frozenset))):
raise TypeError('include should be a list, tuple or set')
if (exclude is not None and
not isinstance(exclude, (list, tuple, set, frozenset))):
raise TypeError('exclude should be a list, tuple or set')
values = {}
for prop in self._properties.itervalues():
name = prop._code_name
if include is not None and name not in include:
continue
if exclude is not None and name in exclude:
continue
try:
values[name] = prop._get_for_dict(self)
except UnprojectedPropertyError:
pass # Ignore unprojected properties rather than failing.
return values | python | 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 excluded.
"""
if (include is not None and
not isinstance(include, (list, tuple, set, frozenset))):
raise TypeError('include should be a list, tuple or set')
if (exclude is not None and
not isinstance(exclude, (list, tuple, set, frozenset))):
raise TypeError('exclude should be a list, tuple or set')
values = {}
for prop in self._properties.itervalues():
name = prop._code_name
if include is not None and name not in include:
continue
if exclude is not None and name in exclude:
continue
try:
values[name] = prop._get_for_dict(self)
except UnprojectedPropertyError:
pass # Ignore unprojected properties rather than failing.
return values | [
"def",
"_to_dict",
"(",
"self",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"(",
"include",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"include",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"frozenset",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'include should be a list, tuple or set'",
")",
"if",
"(",
"exclude",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"exclude",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"frozenset",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'exclude should be a list, tuple or set'",
")",
"values",
"=",
"{",
"}",
"for",
"prop",
"in",
"self",
".",
"_properties",
".",
"itervalues",
"(",
")",
":",
"name",
"=",
"prop",
".",
"_code_name",
"if",
"include",
"is",
"not",
"None",
"and",
"name",
"not",
"in",
"include",
":",
"continue",
"if",
"exclude",
"is",
"not",
"None",
"and",
"name",
"in",
"exclude",
":",
"continue",
"try",
":",
"values",
"[",
"name",
"]",
"=",
"prop",
".",
"_get_for_dict",
"(",
"self",
")",
"except",
"UnprojectedPropertyError",
":",
"pass",
"# Ignore unprojected properties rather than failing.",
"return",
"values"
] | 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. | [
"Return",
"a",
"dict",
"containing",
"the",
"entity",
"s",
"property",
"values",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3278-L3303 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._fix_up_properties | 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 isinstance(kind, basestring):
raise KindError('Class %s defines a _get_kind() method that returns '
'a non-string (%r)' % (cls.__name__, kind))
if not isinstance(kind, str):
try:
kind = kind.encode('ascii') # ASCII contents is okay.
except UnicodeEncodeError:
raise KindError('Class %s defines a _get_kind() method that returns '
'a Unicode string (%r); please encode using utf-8' %
(cls.__name__, kind))
cls._properties = {} # Map of {name: Property}
if cls.__module__ == __name__: # Skip the classes in *this* file.
return
for name in set(dir(cls)):
attr = getattr(cls, name, None)
if isinstance(attr, ModelAttribute) and not isinstance(attr, ModelKey):
if name.startswith('_'):
raise TypeError('ModelAttribute %s cannot begin with an underscore '
'character. _ prefixed attributes are reserved for '
'temporary Model instance values.' % name)
attr._fix_up(cls, name)
if isinstance(attr, Property):
if (attr._repeated or
(isinstance(attr, StructuredProperty) and
attr._modelclass._has_repeated)):
cls._has_repeated = True
cls._properties[attr._name] = attr
cls._update_kind_map() | python | 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 isinstance(kind, basestring):
raise KindError('Class %s defines a _get_kind() method that returns '
'a non-string (%r)' % (cls.__name__, kind))
if not isinstance(kind, str):
try:
kind = kind.encode('ascii') # ASCII contents is okay.
except UnicodeEncodeError:
raise KindError('Class %s defines a _get_kind() method that returns '
'a Unicode string (%r); please encode using utf-8' %
(cls.__name__, kind))
cls._properties = {} # Map of {name: Property}
if cls.__module__ == __name__: # Skip the classes in *this* file.
return
for name in set(dir(cls)):
attr = getattr(cls, name, None)
if isinstance(attr, ModelAttribute) and not isinstance(attr, ModelKey):
if name.startswith('_'):
raise TypeError('ModelAttribute %s cannot begin with an underscore '
'character. _ prefixed attributes are reserved for '
'temporary Model instance values.' % name)
attr._fix_up(cls, name)
if isinstance(attr, Property):
if (attr._repeated or
(isinstance(attr, StructuredProperty) and
attr._modelclass._has_repeated)):
cls._has_repeated = True
cls._properties[attr._name] = attr
cls._update_kind_map() | [
"def",
"_fix_up_properties",
"(",
"cls",
")",
":",
"# Verify that _get_kind() returns an 8-bit string.",
"kind",
"=",
"cls",
".",
"_get_kind",
"(",
")",
"if",
"not",
"isinstance",
"(",
"kind",
",",
"basestring",
")",
":",
"raise",
"KindError",
"(",
"'Class %s defines a _get_kind() method that returns '",
"'a non-string (%r)'",
"%",
"(",
"cls",
".",
"__name__",
",",
"kind",
")",
")",
"if",
"not",
"isinstance",
"(",
"kind",
",",
"str",
")",
":",
"try",
":",
"kind",
"=",
"kind",
".",
"encode",
"(",
"'ascii'",
")",
"# ASCII contents is okay.",
"except",
"UnicodeEncodeError",
":",
"raise",
"KindError",
"(",
"'Class %s defines a _get_kind() method that returns '",
"'a Unicode string (%r); please encode using utf-8'",
"%",
"(",
"cls",
".",
"__name__",
",",
"kind",
")",
")",
"cls",
".",
"_properties",
"=",
"{",
"}",
"# Map of {name: Property}",
"if",
"cls",
".",
"__module__",
"==",
"__name__",
":",
"# Skip the classes in *this* file.",
"return",
"for",
"name",
"in",
"set",
"(",
"dir",
"(",
"cls",
")",
")",
":",
"attr",
"=",
"getattr",
"(",
"cls",
",",
"name",
",",
"None",
")",
"if",
"isinstance",
"(",
"attr",
",",
"ModelAttribute",
")",
"and",
"not",
"isinstance",
"(",
"attr",
",",
"ModelKey",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"raise",
"TypeError",
"(",
"'ModelAttribute %s cannot begin with an underscore '",
"'character. _ prefixed attributes are reserved for '",
"'temporary Model instance values.'",
"%",
"name",
")",
"attr",
".",
"_fix_up",
"(",
"cls",
",",
"name",
")",
"if",
"isinstance",
"(",
"attr",
",",
"Property",
")",
":",
"if",
"(",
"attr",
".",
"_repeated",
"or",
"(",
"isinstance",
"(",
"attr",
",",
"StructuredProperty",
")",
"and",
"attr",
".",
"_modelclass",
".",
"_has_repeated",
")",
")",
":",
"cls",
".",
"_has_repeated",
"=",
"True",
"cls",
".",
"_properties",
"[",
"attr",
".",
"_name",
"]",
"=",
"attr",
"cls",
".",
"_update_kind_map",
"(",
")"
] | 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. | [
"Fix",
"up",
"the",
"properties",
"by",
"calling",
"their",
"_fix_up",
"()",
"method",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3307-L3342 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._check_properties | 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 address subproperties of structured
properties).
Raises:
InvalidPropertyError if one of the properties is invalid.
AssertionError if the argument is not a list or tuple of strings.
"""
assert isinstance(property_names, (list, tuple)), repr(property_names)
for name in property_names:
assert isinstance(name, basestring), repr(name)
if '.' in name:
name, rest = name.split('.', 1)
else:
rest = None
prop = cls._properties.get(name)
if prop is None:
cls._unknown_property(name)
else:
prop._check_property(rest, require_indexed=require_indexed) | python | 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 address subproperties of structured
properties).
Raises:
InvalidPropertyError if one of the properties is invalid.
AssertionError if the argument is not a list or tuple of strings.
"""
assert isinstance(property_names, (list, tuple)), repr(property_names)
for name in property_names:
assert isinstance(name, basestring), repr(name)
if '.' in name:
name, rest = name.split('.', 1)
else:
rest = None
prop = cls._properties.get(name)
if prop is None:
cls._unknown_property(name)
else:
prop._check_property(rest, require_indexed=require_indexed) | [
"def",
"_check_properties",
"(",
"cls",
",",
"property_names",
",",
"require_indexed",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"property_names",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"repr",
"(",
"property_names",
")",
"for",
"name",
"in",
"property_names",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
",",
"repr",
"(",
"name",
")",
"if",
"'.'",
"in",
"name",
":",
"name",
",",
"rest",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"else",
":",
"rest",
"=",
"None",
"prop",
"=",
"cls",
".",
"_properties",
".",
"get",
"(",
"name",
")",
"if",
"prop",
"is",
"None",
":",
"cls",
".",
"_unknown_property",
"(",
"name",
")",
"else",
":",
"prop",
".",
"_check_property",
"(",
"rest",
",",
"require_indexed",
"=",
"require_indexed",
")"
] | 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:
InvalidPropertyError if one of the properties is invalid.
AssertionError if the argument is not a list or tuple of strings. | [
"Internal",
"helper",
"to",
"check",
"the",
"given",
"properties",
"exist",
"and",
"meet",
"specified",
"requirements",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3355-L3381 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._query | 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 distinct.
if 'distinct' in kwds:
if 'group_by' in kwds:
raise TypeError(
'cannot use distinct= and group_by= at the same time')
projection = kwds.get('projection')
if not projection:
raise TypeError(
'cannot use distinct= without projection=')
if kwds.pop('distinct'):
kwds['group_by'] = projection
# TODO: Disallow non-empty args and filter=.
from .query import Query # Import late to avoid circular imports.
qry = Query(kind=cls._get_kind(), **kwds)
qry = qry.filter(*cls._default_filters())
qry = qry.filter(*args)
return qry | python | 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 distinct.
if 'distinct' in kwds:
if 'group_by' in kwds:
raise TypeError(
'cannot use distinct= and group_by= at the same time')
projection = kwds.get('projection')
if not projection:
raise TypeError(
'cannot use distinct= without projection=')
if kwds.pop('distinct'):
kwds['group_by'] = projection
# TODO: Disallow non-empty args and filter=.
from .query import Query # Import late to avoid circular imports.
qry = Query(kind=cls._get_kind(), **kwds)
qry = qry.filter(*cls._default_filters())
qry = qry.filter(*args)
return qry | [
"def",
"_query",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# Validating distinct.",
"if",
"'distinct'",
"in",
"kwds",
":",
"if",
"'group_by'",
"in",
"kwds",
":",
"raise",
"TypeError",
"(",
"'cannot use distinct= and group_by= at the same time'",
")",
"projection",
"=",
"kwds",
".",
"get",
"(",
"'projection'",
")",
"if",
"not",
"projection",
":",
"raise",
"TypeError",
"(",
"'cannot use distinct= without projection='",
")",
"if",
"kwds",
".",
"pop",
"(",
"'distinct'",
")",
":",
"kwds",
"[",
"'group_by'",
"]",
"=",
"projection",
"# TODO: Disallow non-empty args and filter=.",
"from",
".",
"query",
"import",
"Query",
"# Import late to avoid circular imports.",
"qry",
"=",
"Query",
"(",
"kind",
"=",
"cls",
".",
"_get_kind",
"(",
")",
",",
"*",
"*",
"kwds",
")",
"qry",
"=",
"qry",
".",
"filter",
"(",
"*",
"cls",
".",
"_default_filters",
"(",
")",
")",
"qry",
"=",
"qry",
".",
"filter",
"(",
"*",
"args",
")",
"return",
"qry"
] | 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. | [
"Create",
"a",
"Query",
"object",
"for",
"this",
"class",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3410-L3438 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._gql | 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) | python | 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",
"_gql",
"(",
"cls",
",",
"query_string",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"from",
".",
"query",
"import",
"gql",
"# Import late to avoid circular imports.",
"return",
"gql",
"(",
"'SELECT * FROM %s %s'",
"%",
"(",
"cls",
".",
"_class_name",
"(",
")",
",",
"query_string",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")"
] | Run a GQL query. | [
"Run",
"a",
"GQL",
"query",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3442-L3446 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._put_async | 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._prepare_for_put()
if self._key is None:
self._key = Key(self._get_kind(), None)
self._pre_put_hook()
fut = ctx.put(self, **ctx_options)
post_hook = self._post_put_hook
if not self._is_default_hook(Model._default_post_put_hook, post_hook):
fut.add_immediate_callback(post_hook, fut)
return fut | python | 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._prepare_for_put()
if self._key is None:
self._key = Key(self._get_kind(), None)
self._pre_put_hook()
fut = ctx.put(self, **ctx_options)
post_hook = self._post_put_hook
if not self._is_default_hook(Model._default_post_put_hook, post_hook):
fut.add_immediate_callback(post_hook, fut)
return fut | [
"def",
"_put_async",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
":",
"if",
"self",
".",
"_projection",
":",
"raise",
"datastore_errors",
".",
"BadRequestError",
"(",
"'Cannot put a partial entity'",
")",
"from",
".",
"import",
"tasklets",
"ctx",
"=",
"tasklets",
".",
"get_context",
"(",
")",
"self",
".",
"_prepare_for_put",
"(",
")",
"if",
"self",
".",
"_key",
"is",
"None",
":",
"self",
".",
"_key",
"=",
"Key",
"(",
"self",
".",
"_get_kind",
"(",
")",
",",
"None",
")",
"self",
".",
"_pre_put_hook",
"(",
")",
"fut",
"=",
"ctx",
".",
"put",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
"post_hook",
"=",
"self",
".",
"_post_put_hook",
"if",
"not",
"self",
".",
"_is_default_hook",
"(",
"Model",
".",
"_default_post_put_hook",
",",
"post_hook",
")",
":",
"fut",
".",
"add_immediate_callback",
"(",
"post_hook",
",",
"fut",
")",
"return",
"fut"
] | Write this entity to Cloud Datastore.
This is the asynchronous version of Model._put(). | [
"Write",
"this",
"entity",
"to",
"Cloud",
"Datastore",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3461-L3478 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._get_or_insert | 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_options: ContextOptions object (not keyword args!) or None.
**kwds: Keyword arguments to pass to the constructor of the model class
if an instance for the specified key name does not already exist. If
an instance with the supplied key_name and parent already exists,
these arguments will be discarded.
Returns:
Existing instance of Model class with the specified key name and parent
or a new one that has just been created.
"""
cls, args = args[0], args[1:]
return cls._get_or_insert_async(*args, **kwds).get_result() | python | 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_options: ContextOptions object (not keyword args!) or None.
**kwds: Keyword arguments to pass to the constructor of the model class
if an instance for the specified key name does not already exist. If
an instance with the supplied key_name and parent already exists,
these arguments will be discarded.
Returns:
Existing instance of Model class with the specified key name and parent
or a new one that has just been created.
"""
cls, args = args[0], args[1:]
return cls._get_or_insert_async(*args, **kwds).get_result() | [
"def",
"_get_or_insert",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"cls",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
"return",
"cls",
".",
"_get_or_insert_async",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
".",
"get_result",
"(",
")"
] | 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!) or None.
**kwds: Keyword arguments to pass to the constructor of the model class
if an instance for the specified key name does not already exist. If
an instance with the supplied key_name and parent already exists,
these arguments will be discarded.
Returns:
Existing instance of Model class with the specified key name and parent
or a new one that has just been created. | [
"Transactionally",
"retrieves",
"an",
"existing",
"entity",
"or",
"creates",
"a",
"new",
"one",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3482-L3503 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._get_or_insert_async | 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'.
from . import tasklets
cls, name = args # These must always be positional.
get_arg = cls.__get_arg
app = get_arg(kwds, 'app')
namespace = get_arg(kwds, 'namespace')
parent = get_arg(kwds, 'parent')
context_options = get_arg(kwds, 'context_options')
# (End of super-special argument parsing.)
# TODO: Test the heck out of this, in all sorts of evil scenarios.
if not isinstance(name, basestring):
raise TypeError('name must be a string; received %r' % name)
elif not name:
raise ValueError('name cannot be an empty string.')
key = Key(cls, name, app=app, namespace=namespace, parent=parent)
@tasklets.tasklet
def internal_tasklet():
@tasklets.tasklet
def txn():
ent = yield key.get_async(options=context_options)
if ent is None:
ent = cls(**kwds) # TODO: Use _populate().
ent._key = key
yield ent.put_async(options=context_options)
raise tasklets.Return(ent)
if in_transaction():
# Run txn() in existing transaction.
ent = yield txn()
else:
# Maybe avoid a transaction altogether.
ent = yield key.get_async(options=context_options)
if ent is None:
# Run txn() in new transaction.
ent = yield transaction_async(txn)
raise tasklets.Return(ent)
return internal_tasklet() | python | 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'.
from . import tasklets
cls, name = args # These must always be positional.
get_arg = cls.__get_arg
app = get_arg(kwds, 'app')
namespace = get_arg(kwds, 'namespace')
parent = get_arg(kwds, 'parent')
context_options = get_arg(kwds, 'context_options')
# (End of super-special argument parsing.)
# TODO: Test the heck out of this, in all sorts of evil scenarios.
if not isinstance(name, basestring):
raise TypeError('name must be a string; received %r' % name)
elif not name:
raise ValueError('name cannot be an empty string.')
key = Key(cls, name, app=app, namespace=namespace, parent=parent)
@tasklets.tasklet
def internal_tasklet():
@tasklets.tasklet
def txn():
ent = yield key.get_async(options=context_options)
if ent is None:
ent = cls(**kwds) # TODO: Use _populate().
ent._key = key
yield ent.put_async(options=context_options)
raise tasklets.Return(ent)
if in_transaction():
# Run txn() in existing transaction.
ent = yield txn()
else:
# Maybe avoid a transaction altogether.
ent = yield key.get_async(options=context_options)
if ent is None:
# Run txn() in new transaction.
ent = yield transaction_async(txn)
raise tasklets.Return(ent)
return internal_tasklet() | [
"def",
"_get_or_insert_async",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# NOTE: The signature is really weird here because we want to support",
"# models with properties named e.g. 'cls' or 'name'.",
"from",
".",
"import",
"tasklets",
"cls",
",",
"name",
"=",
"args",
"# These must always be positional.",
"get_arg",
"=",
"cls",
".",
"__get_arg",
"app",
"=",
"get_arg",
"(",
"kwds",
",",
"'app'",
")",
"namespace",
"=",
"get_arg",
"(",
"kwds",
",",
"'namespace'",
")",
"parent",
"=",
"get_arg",
"(",
"kwds",
",",
"'parent'",
")",
"context_options",
"=",
"get_arg",
"(",
"kwds",
",",
"'context_options'",
")",
"# (End of super-special argument parsing.)",
"# TODO: Test the heck out of this, in all sorts of evil scenarios.",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'name must be a string; received %r'",
"%",
"name",
")",
"elif",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"'name cannot be an empty string.'",
")",
"key",
"=",
"Key",
"(",
"cls",
",",
"name",
",",
"app",
"=",
"app",
",",
"namespace",
"=",
"namespace",
",",
"parent",
"=",
"parent",
")",
"@",
"tasklets",
".",
"tasklet",
"def",
"internal_tasklet",
"(",
")",
":",
"@",
"tasklets",
".",
"tasklet",
"def",
"txn",
"(",
")",
":",
"ent",
"=",
"yield",
"key",
".",
"get_async",
"(",
"options",
"=",
"context_options",
")",
"if",
"ent",
"is",
"None",
":",
"ent",
"=",
"cls",
"(",
"*",
"*",
"kwds",
")",
"# TODO: Use _populate().",
"ent",
".",
"_key",
"=",
"key",
"yield",
"ent",
".",
"put_async",
"(",
"options",
"=",
"context_options",
")",
"raise",
"tasklets",
".",
"Return",
"(",
"ent",
")",
"if",
"in_transaction",
"(",
")",
":",
"# Run txn() in existing transaction.",
"ent",
"=",
"yield",
"txn",
"(",
")",
"else",
":",
"# Maybe avoid a transaction altogether.",
"ent",
"=",
"yield",
"key",
".",
"get_async",
"(",
"options",
"=",
"context_options",
")",
"if",
"ent",
"is",
"None",
":",
"# Run txn() in new transaction.",
"ent",
"=",
"yield",
"transaction_async",
"(",
"txn",
")",
"raise",
"tasklets",
".",
"Return",
"(",
"ent",
")",
"return",
"internal_tasklet",
"(",
")"
] | Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert(). | [
"Transactionally",
"retrieves",
"an",
"existing",
"entity",
"or",
"creates",
"a",
"new",
"one",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3507-L3550 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._allocate_ids | 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 both.
parent: Parent key for which the IDs will be allocated.
**ctx_options: Context options.
Returns:
A tuple with (start, end) for the allocated range, inclusive.
"""
return cls._allocate_ids_async(size=size, max=max, parent=parent,
**ctx_options).get_result() | python | 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 both.
parent: Parent key for which the IDs will be allocated.
**ctx_options: Context options.
Returns:
A tuple with (start, end) for the allocated range, inclusive.
"""
return cls._allocate_ids_async(size=size, max=max, parent=parent,
**ctx_options).get_result() | [
"def",
"_allocate_ids",
"(",
"cls",
",",
"size",
"=",
"None",
",",
"max",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"ctx_options",
")",
":",
"return",
"cls",
".",
"_allocate_ids_async",
"(",
"size",
"=",
"size",
",",
"max",
"=",
"max",
",",
"parent",
"=",
"parent",
",",
"*",
"*",
"ctx_options",
")",
".",
"get_result",
"(",
")"
] | 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_options: Context options.
Returns:
A tuple with (start, end) for the allocated range, inclusive. | [
"Allocates",
"a",
"range",
"of",
"key",
"IDs",
"for",
"this",
"model",
"class",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3555-L3570 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._allocate_ids_async | 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_hook(size, max, parent)
key = Key(cls._get_kind(), None, parent=parent)
fut = ctx.allocate_ids(key, size=size, max=max, **ctx_options)
post_hook = cls._post_allocate_ids_hook
if not cls._is_default_hook(Model._default_post_allocate_ids_hook,
post_hook):
fut.add_immediate_callback(post_hook, size, max, parent, fut)
return fut | python | 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_hook(size, max, parent)
key = Key(cls._get_kind(), None, parent=parent)
fut = ctx.allocate_ids(key, size=size, max=max, **ctx_options)
post_hook = cls._post_allocate_ids_hook
if not cls._is_default_hook(Model._default_post_allocate_ids_hook,
post_hook):
fut.add_immediate_callback(post_hook, size, max, parent, fut)
return fut | [
"def",
"_allocate_ids_async",
"(",
"cls",
",",
"size",
"=",
"None",
",",
"max",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"ctx_options",
")",
":",
"from",
".",
"import",
"tasklets",
"ctx",
"=",
"tasklets",
".",
"get_context",
"(",
")",
"cls",
".",
"_pre_allocate_ids_hook",
"(",
"size",
",",
"max",
",",
"parent",
")",
"key",
"=",
"Key",
"(",
"cls",
".",
"_get_kind",
"(",
")",
",",
"None",
",",
"parent",
"=",
"parent",
")",
"fut",
"=",
"ctx",
".",
"allocate_ids",
"(",
"key",
",",
"size",
"=",
"size",
",",
"max",
"=",
"max",
",",
"*",
"*",
"ctx_options",
")",
"post_hook",
"=",
"cls",
".",
"_post_allocate_ids_hook",
"if",
"not",
"cls",
".",
"_is_default_hook",
"(",
"Model",
".",
"_default_post_allocate_ids_hook",
",",
"post_hook",
")",
":",
"fut",
".",
"add_immediate_callback",
"(",
"post_hook",
",",
"size",
",",
"max",
",",
"parent",
",",
"fut",
")",
"return",
"fut"
] | Allocates a range of key IDs for this model class.
This is the asynchronous version of Model._allocate_ids(). | [
"Allocates",
"a",
"range",
"of",
"key",
"IDs",
"for",
"this",
"model",
"class",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3574-L3589 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._get_by_id | 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: Optional app ID.
**ctx_options: Context options.
Returns:
A model instance or None if not found.
"""
return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result() | python | 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: Optional app ID.
**ctx_options: Context options.
Returns:
A model instance or None if not found.
"""
return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result() | [
"def",
"_get_by_id",
"(",
"cls",
",",
"id",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"ctx_options",
")",
":",
"return",
"cls",
".",
"_get_by_id_async",
"(",
"id",
",",
"parent",
"=",
"parent",
",",
"*",
"*",
"ctx_options",
")",
".",
"get_result",
"(",
")"
] | 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:
A model instance or None if not found. | [
"Returns",
"an",
"instance",
"of",
"Model",
"class",
"by",
"ID",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3594-L3609 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._get_by_id_async | 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=namespace)
return key.get_async(**ctx_options) | python | 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=namespace)
return key.get_async(**ctx_options) | [
"def",
"_get_by_id_async",
"(",
"cls",
",",
"id",
",",
"parent",
"=",
"None",
",",
"app",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"ctx_options",
")",
":",
"key",
"=",
"Key",
"(",
"cls",
".",
"_get_kind",
"(",
")",
",",
"id",
",",
"parent",
"=",
"parent",
",",
"app",
"=",
"app",
",",
"namespace",
"=",
"namespace",
")",
"return",
"key",
".",
"get_async",
"(",
"*",
"*",
"ctx_options",
")"
] | Returns an instance of Model class by ID (and app, namespace).
This is the asynchronous version of Model._get_by_id(). | [
"Returns",
"an",
"instance",
"of",
"Model",
"class",
"by",
"ID",
"(",
"and",
"app",
"namespace",
")",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3614-L3621 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/model.py | Model._is_default_hook | 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:
TypeError if either the default hook or the tested hook are not callable.
"""
if not hasattr(default_hook, '__call__'):
raise TypeError('Default hooks for ndb.model.Model must be callable')
if not hasattr(hook, '__call__'):
raise TypeError('Hooks must be callable')
return default_hook.im_func is hook.im_func | python | 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:
TypeError if either the default hook or the tested hook are not callable.
"""
if not hasattr(default_hook, '__call__'):
raise TypeError('Default hooks for ndb.model.Model must be callable')
if not hasattr(hook, '__call__'):
raise TypeError('Hooks must be callable')
return default_hook.im_func is hook.im_func | [
"def",
"_is_default_hook",
"(",
"default_hook",
",",
"hook",
")",
":",
"if",
"not",
"hasattr",
"(",
"default_hook",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Default hooks for ndb.model.Model must be callable'",
")",
"if",
"not",
"hasattr",
"(",
"hook",
",",
"'__call__'",
")",
":",
"raise",
"TypeError",
"(",
"'Hooks must be callable'",
")",
"return",
"default_hook",
".",
"im_func",
"is",
"hook",
".",
"im_func"
] | 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 are not callable. | [
"Checks",
"whether",
"a",
"specific",
"hook",
"is",
"in",
"its",
"default",
"state",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3676-L3691 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | _ConstructReference | 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 reference on non-Key class; '
'received %r' % cls)
if (bool(pairs) + bool(flat) + bool(reference) + bool(serialized) +
bool(urlsafe)) != 1:
raise TypeError('Cannot construct Key reference from incompatible keyword '
'arguments.')
if flat or pairs:
if flat:
if len(flat) % 2:
raise TypeError('_ConstructReference() must have an even number of '
'positional arguments.')
pairs = [(flat[i], flat[i + 1]) for i in xrange(0, len(flat), 2)]
elif parent is not None:
pairs = list(pairs)
if not pairs:
raise TypeError('Key references must consist of at least one pair.')
if parent is not None:
if not isinstance(parent, Key):
raise datastore_errors.BadValueError(
'Expected Key instance, got %r' % parent)
pairs[:0] = parent.pairs()
if app:
if app != parent.app():
raise ValueError('Cannot specify a different app %r '
'than the parent app %r' %
(app, parent.app()))
else:
app = parent.app()
if namespace is not None:
if namespace != parent.namespace():
raise ValueError('Cannot specify a different namespace %r '
'than the parent namespace %r' %
(namespace, parent.namespace()))
else:
namespace = parent.namespace()
reference = _ReferenceFromPairs(pairs, app=app, namespace=namespace)
else:
if parent is not None:
raise TypeError('Key reference cannot be constructed when the parent '
'argument is combined with either reference, serialized '
'or urlsafe arguments.')
if urlsafe:
serialized = _DecodeUrlSafe(urlsafe)
if serialized:
reference = _ReferenceFromSerialized(serialized)
if not reference.path().element_size():
raise RuntimeError('Key reference has no path or elements (%r, %r, %r).'
% (urlsafe, serialized, str(reference)))
# TODO: ensure that each element has a type and either an id or a name
if not serialized:
reference = _ReferenceFromReference(reference)
# You needn't specify app= or namespace= together with reference=,
# serialized= or urlsafe=, but if you do, their values must match
# what is already in the reference.
if app is not None:
ref_app = reference.app()
if app != ref_app:
raise RuntimeError('Key reference constructed uses a different app %r '
'than the one specified %r' %
(ref_app, app))
if namespace is not None:
ref_namespace = reference.name_space()
if namespace != ref_namespace:
raise RuntimeError('Key reference constructed uses a different '
'namespace %r than the one specified %r' %
(ref_namespace, namespace))
return reference | python | 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 reference on non-Key class; '
'received %r' % cls)
if (bool(pairs) + bool(flat) + bool(reference) + bool(serialized) +
bool(urlsafe)) != 1:
raise TypeError('Cannot construct Key reference from incompatible keyword '
'arguments.')
if flat or pairs:
if flat:
if len(flat) % 2:
raise TypeError('_ConstructReference() must have an even number of '
'positional arguments.')
pairs = [(flat[i], flat[i + 1]) for i in xrange(0, len(flat), 2)]
elif parent is not None:
pairs = list(pairs)
if not pairs:
raise TypeError('Key references must consist of at least one pair.')
if parent is not None:
if not isinstance(parent, Key):
raise datastore_errors.BadValueError(
'Expected Key instance, got %r' % parent)
pairs[:0] = parent.pairs()
if app:
if app != parent.app():
raise ValueError('Cannot specify a different app %r '
'than the parent app %r' %
(app, parent.app()))
else:
app = parent.app()
if namespace is not None:
if namespace != parent.namespace():
raise ValueError('Cannot specify a different namespace %r '
'than the parent namespace %r' %
(namespace, parent.namespace()))
else:
namespace = parent.namespace()
reference = _ReferenceFromPairs(pairs, app=app, namespace=namespace)
else:
if parent is not None:
raise TypeError('Key reference cannot be constructed when the parent '
'argument is combined with either reference, serialized '
'or urlsafe arguments.')
if urlsafe:
serialized = _DecodeUrlSafe(urlsafe)
if serialized:
reference = _ReferenceFromSerialized(serialized)
if not reference.path().element_size():
raise RuntimeError('Key reference has no path or elements (%r, %r, %r).'
% (urlsafe, serialized, str(reference)))
# TODO: ensure that each element has a type and either an id or a name
if not serialized:
reference = _ReferenceFromReference(reference)
# You needn't specify app= or namespace= together with reference=,
# serialized= or urlsafe=, but if you do, their values must match
# what is already in the reference.
if app is not None:
ref_app = reference.app()
if app != ref_app:
raise RuntimeError('Key reference constructed uses a different app %r '
'than the one specified %r' %
(ref_app, app))
if namespace is not None:
ref_namespace = reference.name_space()
if namespace != ref_namespace:
raise RuntimeError('Key reference constructed uses a different '
'namespace %r than the one specified %r' %
(ref_namespace, namespace))
return reference | [
"def",
"_ConstructReference",
"(",
"cls",
",",
"pairs",
"=",
"None",
",",
"flat",
"=",
"None",
",",
"reference",
"=",
"None",
",",
"serialized",
"=",
"None",
",",
"urlsafe",
"=",
"None",
",",
"app",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"not",
"Key",
":",
"raise",
"TypeError",
"(",
"'Cannot construct Key reference on non-Key class; '",
"'received %r'",
"%",
"cls",
")",
"if",
"(",
"bool",
"(",
"pairs",
")",
"+",
"bool",
"(",
"flat",
")",
"+",
"bool",
"(",
"reference",
")",
"+",
"bool",
"(",
"serialized",
")",
"+",
"bool",
"(",
"urlsafe",
")",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"'Cannot construct Key reference from incompatible keyword '",
"'arguments.'",
")",
"if",
"flat",
"or",
"pairs",
":",
"if",
"flat",
":",
"if",
"len",
"(",
"flat",
")",
"%",
"2",
":",
"raise",
"TypeError",
"(",
"'_ConstructReference() must have an even number of '",
"'positional arguments.'",
")",
"pairs",
"=",
"[",
"(",
"flat",
"[",
"i",
"]",
",",
"flat",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"flat",
")",
",",
"2",
")",
"]",
"elif",
"parent",
"is",
"not",
"None",
":",
"pairs",
"=",
"list",
"(",
"pairs",
")",
"if",
"not",
"pairs",
":",
"raise",
"TypeError",
"(",
"'Key references must consist of at least one pair.'",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"parent",
",",
"Key",
")",
":",
"raise",
"datastore_errors",
".",
"BadValueError",
"(",
"'Expected Key instance, got %r'",
"%",
"parent",
")",
"pairs",
"[",
":",
"0",
"]",
"=",
"parent",
".",
"pairs",
"(",
")",
"if",
"app",
":",
"if",
"app",
"!=",
"parent",
".",
"app",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot specify a different app %r '",
"'than the parent app %r'",
"%",
"(",
"app",
",",
"parent",
".",
"app",
"(",
")",
")",
")",
"else",
":",
"app",
"=",
"parent",
".",
"app",
"(",
")",
"if",
"namespace",
"is",
"not",
"None",
":",
"if",
"namespace",
"!=",
"parent",
".",
"namespace",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot specify a different namespace %r '",
"'than the parent namespace %r'",
"%",
"(",
"namespace",
",",
"parent",
".",
"namespace",
"(",
")",
")",
")",
"else",
":",
"namespace",
"=",
"parent",
".",
"namespace",
"(",
")",
"reference",
"=",
"_ReferenceFromPairs",
"(",
"pairs",
",",
"app",
"=",
"app",
",",
"namespace",
"=",
"namespace",
")",
"else",
":",
"if",
"parent",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'Key reference cannot be constructed when the parent '",
"'argument is combined with either reference, serialized '",
"'or urlsafe arguments.'",
")",
"if",
"urlsafe",
":",
"serialized",
"=",
"_DecodeUrlSafe",
"(",
"urlsafe",
")",
"if",
"serialized",
":",
"reference",
"=",
"_ReferenceFromSerialized",
"(",
"serialized",
")",
"if",
"not",
"reference",
".",
"path",
"(",
")",
".",
"element_size",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Key reference has no path or elements (%r, %r, %r).'",
"%",
"(",
"urlsafe",
",",
"serialized",
",",
"str",
"(",
"reference",
")",
")",
")",
"# TODO: ensure that each element has a type and either an id or a name",
"if",
"not",
"serialized",
":",
"reference",
"=",
"_ReferenceFromReference",
"(",
"reference",
")",
"# You needn't specify app= or namespace= together with reference=,",
"# serialized= or urlsafe=, but if you do, their values must match",
"# what is already in the reference.",
"if",
"app",
"is",
"not",
"None",
":",
"ref_app",
"=",
"reference",
".",
"app",
"(",
")",
"if",
"app",
"!=",
"ref_app",
":",
"raise",
"RuntimeError",
"(",
"'Key reference constructed uses a different app %r '",
"'than the one specified %r'",
"%",
"(",
"ref_app",
",",
"app",
")",
")",
"if",
"namespace",
"is",
"not",
"None",
":",
"ref_namespace",
"=",
"reference",
".",
"name_space",
"(",
")",
"if",
"namespace",
"!=",
"ref_namespace",
":",
"raise",
"RuntimeError",
"(",
"'Key reference constructed uses a different '",
"'namespace %r than the one specified %r'",
"%",
"(",
"ref_namespace",
",",
"namespace",
")",
")",
"return",
"reference"
] | Construct a Reference; the signature is the same as for Key. | [
"Construct",
"a",
"Reference",
";",
"the",
"signature",
"is",
"the",
"same",
"as",
"for",
"Key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L633-L704 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | _ReferenceFromPairs | 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 reference is None:
reference = entity_pb.Reference()
path = reference.mutable_path()
last = False
for kind, idorname in pairs:
if last:
raise datastore_errors.BadArgumentError(
'Incomplete Key entry must be last')
t = type(kind)
if t is str:
pass
elif t is unicode:
kind = kind.encode('utf8')
else:
if issubclass(t, type):
# Late import to avoid cycles.
from .model import Model
modelclass = kind
if not issubclass(modelclass, Model):
raise TypeError('Key kind must be either a string or subclass of '
'Model; received %r' % modelclass)
kind = modelclass._get_kind()
t = type(kind)
if t is str:
pass
elif t is unicode:
kind = kind.encode('utf8')
elif issubclass(t, str):
pass
elif issubclass(t, unicode):
kind = kind.encode('utf8')
else:
raise TypeError('Key kind must be either a string or subclass of Model;'
' received %r' % kind)
# pylint: disable=superfluous-parens
if not (1 <= len(kind) <= _MAX_KEYPART_BYTES):
raise ValueError('Key kind string must be a non-empty string up to %i'
'bytes; received %s' %
(_MAX_KEYPART_BYTES, kind))
elem = path.add_element()
elem.set_type(kind)
t = type(idorname)
if t is int or t is long:
# pylint: disable=superfluous-parens
if not (1 <= idorname < _MAX_LONG):
raise ValueError('Key id number is too long; received %i' % idorname)
elem.set_id(idorname)
elif t is str:
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name strings must be non-empty strings up to %i '
'bytes; received %s' %
(_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
elif t is unicode:
idorname = idorname.encode('utf8')
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name unicode strings must be non-empty strings up'
' to %i bytes; received %s' %
(_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
elif idorname is None:
last = True
elif issubclass(t, (int, long)):
# pylint: disable=superfluous-parens
if not (1 <= idorname < _MAX_LONG):
raise ValueError('Key id number is too long; received %i' % idorname)
elem.set_id(idorname)
elif issubclass(t, basestring):
if issubclass(t, unicode):
idorname = idorname.encode('utf8')
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name strings must be non-empty strings up to %i '
'bytes; received %s' % (_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
else:
raise TypeError('id must be either a numeric id or a string name; '
'received %r' % idorname)
# An empty app id means to use the default app id.
if not app:
app = _DefaultAppId()
# Always set the app id, since it is mandatory.
reference.set_app(app)
# An empty namespace overrides the default namespace.
if namespace is None:
namespace = _DefaultNamespace()
# Only set the namespace if it is not empty.
if namespace:
reference.set_name_space(namespace)
return reference | python | 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 reference is None:
reference = entity_pb.Reference()
path = reference.mutable_path()
last = False
for kind, idorname in pairs:
if last:
raise datastore_errors.BadArgumentError(
'Incomplete Key entry must be last')
t = type(kind)
if t is str:
pass
elif t is unicode:
kind = kind.encode('utf8')
else:
if issubclass(t, type):
# Late import to avoid cycles.
from .model import Model
modelclass = kind
if not issubclass(modelclass, Model):
raise TypeError('Key kind must be either a string or subclass of '
'Model; received %r' % modelclass)
kind = modelclass._get_kind()
t = type(kind)
if t is str:
pass
elif t is unicode:
kind = kind.encode('utf8')
elif issubclass(t, str):
pass
elif issubclass(t, unicode):
kind = kind.encode('utf8')
else:
raise TypeError('Key kind must be either a string or subclass of Model;'
' received %r' % kind)
# pylint: disable=superfluous-parens
if not (1 <= len(kind) <= _MAX_KEYPART_BYTES):
raise ValueError('Key kind string must be a non-empty string up to %i'
'bytes; received %s' %
(_MAX_KEYPART_BYTES, kind))
elem = path.add_element()
elem.set_type(kind)
t = type(idorname)
if t is int or t is long:
# pylint: disable=superfluous-parens
if not (1 <= idorname < _MAX_LONG):
raise ValueError('Key id number is too long; received %i' % idorname)
elem.set_id(idorname)
elif t is str:
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name strings must be non-empty strings up to %i '
'bytes; received %s' %
(_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
elif t is unicode:
idorname = idorname.encode('utf8')
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name unicode strings must be non-empty strings up'
' to %i bytes; received %s' %
(_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
elif idorname is None:
last = True
elif issubclass(t, (int, long)):
# pylint: disable=superfluous-parens
if not (1 <= idorname < _MAX_LONG):
raise ValueError('Key id number is too long; received %i' % idorname)
elem.set_id(idorname)
elif issubclass(t, basestring):
if issubclass(t, unicode):
idorname = idorname.encode('utf8')
# pylint: disable=superfluous-parens
if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
raise ValueError('Key name strings must be non-empty strings up to %i '
'bytes; received %s' % (_MAX_KEYPART_BYTES, idorname))
elem.set_name(idorname)
else:
raise TypeError('id must be either a numeric id or a string name; '
'received %r' % idorname)
# An empty app id means to use the default app id.
if not app:
app = _DefaultAppId()
# Always set the app id, since it is mandatory.
reference.set_app(app)
# An empty namespace overrides the default namespace.
if namespace is None:
namespace = _DefaultNamespace()
# Only set the namespace if it is not empty.
if namespace:
reference.set_name_space(namespace)
return reference | [
"def",
"_ReferenceFromPairs",
"(",
"pairs",
",",
"reference",
"=",
"None",
",",
"app",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"reference",
"=",
"entity_pb",
".",
"Reference",
"(",
")",
"path",
"=",
"reference",
".",
"mutable_path",
"(",
")",
"last",
"=",
"False",
"for",
"kind",
",",
"idorname",
"in",
"pairs",
":",
"if",
"last",
":",
"raise",
"datastore_errors",
".",
"BadArgumentError",
"(",
"'Incomplete Key entry must be last'",
")",
"t",
"=",
"type",
"(",
"kind",
")",
"if",
"t",
"is",
"str",
":",
"pass",
"elif",
"t",
"is",
"unicode",
":",
"kind",
"=",
"kind",
".",
"encode",
"(",
"'utf8'",
")",
"else",
":",
"if",
"issubclass",
"(",
"t",
",",
"type",
")",
":",
"# Late import to avoid cycles.",
"from",
".",
"model",
"import",
"Model",
"modelclass",
"=",
"kind",
"if",
"not",
"issubclass",
"(",
"modelclass",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"'Key kind must be either a string or subclass of '",
"'Model; received %r'",
"%",
"modelclass",
")",
"kind",
"=",
"modelclass",
".",
"_get_kind",
"(",
")",
"t",
"=",
"type",
"(",
"kind",
")",
"if",
"t",
"is",
"str",
":",
"pass",
"elif",
"t",
"is",
"unicode",
":",
"kind",
"=",
"kind",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"issubclass",
"(",
"t",
",",
"str",
")",
":",
"pass",
"elif",
"issubclass",
"(",
"t",
",",
"unicode",
")",
":",
"kind",
"=",
"kind",
".",
"encode",
"(",
"'utf8'",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Key kind must be either a string or subclass of Model;'",
"' received %r'",
"%",
"kind",
")",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"len",
"(",
"kind",
")",
"<=",
"_MAX_KEYPART_BYTES",
")",
":",
"raise",
"ValueError",
"(",
"'Key kind string must be a non-empty string up to %i'",
"'bytes; received %s'",
"%",
"(",
"_MAX_KEYPART_BYTES",
",",
"kind",
")",
")",
"elem",
"=",
"path",
".",
"add_element",
"(",
")",
"elem",
".",
"set_type",
"(",
"kind",
")",
"t",
"=",
"type",
"(",
"idorname",
")",
"if",
"t",
"is",
"int",
"or",
"t",
"is",
"long",
":",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"idorname",
"<",
"_MAX_LONG",
")",
":",
"raise",
"ValueError",
"(",
"'Key id number is too long; received %i'",
"%",
"idorname",
")",
"elem",
".",
"set_id",
"(",
"idorname",
")",
"elif",
"t",
"is",
"str",
":",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"len",
"(",
"idorname",
")",
"<=",
"_MAX_KEYPART_BYTES",
")",
":",
"raise",
"ValueError",
"(",
"'Key name strings must be non-empty strings up to %i '",
"'bytes; received %s'",
"%",
"(",
"_MAX_KEYPART_BYTES",
",",
"idorname",
")",
")",
"elem",
".",
"set_name",
"(",
"idorname",
")",
"elif",
"t",
"is",
"unicode",
":",
"idorname",
"=",
"idorname",
".",
"encode",
"(",
"'utf8'",
")",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"len",
"(",
"idorname",
")",
"<=",
"_MAX_KEYPART_BYTES",
")",
":",
"raise",
"ValueError",
"(",
"'Key name unicode strings must be non-empty strings up'",
"' to %i bytes; received %s'",
"%",
"(",
"_MAX_KEYPART_BYTES",
",",
"idorname",
")",
")",
"elem",
".",
"set_name",
"(",
"idorname",
")",
"elif",
"idorname",
"is",
"None",
":",
"last",
"=",
"True",
"elif",
"issubclass",
"(",
"t",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"idorname",
"<",
"_MAX_LONG",
")",
":",
"raise",
"ValueError",
"(",
"'Key id number is too long; received %i'",
"%",
"idorname",
")",
"elem",
".",
"set_id",
"(",
"idorname",
")",
"elif",
"issubclass",
"(",
"t",
",",
"basestring",
")",
":",
"if",
"issubclass",
"(",
"t",
",",
"unicode",
")",
":",
"idorname",
"=",
"idorname",
".",
"encode",
"(",
"'utf8'",
")",
"# pylint: disable=superfluous-parens",
"if",
"not",
"(",
"1",
"<=",
"len",
"(",
"idorname",
")",
"<=",
"_MAX_KEYPART_BYTES",
")",
":",
"raise",
"ValueError",
"(",
"'Key name strings must be non-empty strings up to %i '",
"'bytes; received %s'",
"%",
"(",
"_MAX_KEYPART_BYTES",
",",
"idorname",
")",
")",
"elem",
".",
"set_name",
"(",
"idorname",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'id must be either a numeric id or a string name; '",
"'received %r'",
"%",
"idorname",
")",
"# An empty app id means to use the default app id.",
"if",
"not",
"app",
":",
"app",
"=",
"_DefaultAppId",
"(",
")",
"# Always set the app id, since it is mandatory.",
"reference",
".",
"set_app",
"(",
"app",
")",
"# An empty namespace overrides the default namespace.",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"_DefaultNamespace",
"(",
")",
"# Only set the namespace if it is not empty.",
"if",
"namespace",
":",
"reference",
".",
"set_name_space",
"(",
"namespace",
")",
"return",
"reference"
] | 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. | [
"Construct",
"a",
"Reference",
"from",
"a",
"list",
"of",
"pairs",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L707-L805 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | _ReferenceFromSerialized | 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 entity_pb.Reference(serialized) | python | 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 entity_pb.Reference(serialized) | [
"def",
"_ReferenceFromSerialized",
"(",
"serialized",
")",
":",
"if",
"not",
"isinstance",
"(",
"serialized",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'serialized must be a string; received %r'",
"%",
"serialized",
")",
"elif",
"isinstance",
"(",
"serialized",
",",
"unicode",
")",
":",
"serialized",
"=",
"serialized",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"entity_pb",
".",
"Reference",
"(",
"serialized",
")"
] | Construct a Reference from a serialized Reference. | [
"Construct",
"a",
"Reference",
"from",
"a",
"serialized",
"Reference",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L815-L821 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | _DecodeUrlSafe | 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(urlsafe) % 4
if mod:
urlsafe += '=' * (4 - mod)
# This is 3-4x faster than urlsafe_b64decode()
return base64.b64decode(urlsafe.replace('-', '+').replace('_', '/')) | python | 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(urlsafe) % 4
if mod:
urlsafe += '=' * (4 - mod)
# This is 3-4x faster than urlsafe_b64decode()
return base64.b64decode(urlsafe.replace('-', '+').replace('_', '/')) | [
"def",
"_DecodeUrlSafe",
"(",
"urlsafe",
")",
":",
"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",
"(",
"urlsafe",
")",
"%",
"4",
"if",
"mod",
":",
"urlsafe",
"+=",
"'='",
"*",
"(",
"4",
"-",
"mod",
")",
"# This is 3-4x faster than urlsafe_b64decode()",
"return",
"base64",
".",
"b64decode",
"(",
"urlsafe",
".",
"replace",
"(",
"'-'",
",",
"'+'",
")",
".",
"replace",
"(",
"'_'",
",",
"'/'",
")",
")"
] | Decode a url-safe base64-encoded string.
This returns the decoded string. | [
"Decode",
"a",
"url",
"-",
"safe",
"base64",
"-",
"encoded",
"string",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L824-L837 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key._parse_from_ref | 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 reference on non-Key class; '
'received %r' % cls)
if (bool(pairs) + bool(flat) + bool(reference) + bool(serialized) +
bool(urlsafe) + bool(parent)) != 1:
raise TypeError('Cannot construct Key reference from incompatible '
'keyword arguments.')
if urlsafe:
serialized = _DecodeUrlSafe(urlsafe)
if serialized:
reference = _ReferenceFromSerialized(serialized)
if reference:
reference = _ReferenceFromReference(reference)
pairs = []
elem = None
path = reference.path()
for elem in path.element_list():
kind = elem.type()
if elem.has_id():
id_or_name = elem.id()
else:
id_or_name = elem.name()
if not id_or_name:
id_or_name = None
tup = (kind, id_or_name)
pairs.append(tup)
if elem is None:
raise RuntimeError('Key reference has no path or elements (%r, %r, %r).'
% (urlsafe, serialized, str(reference)))
# TODO: ensure that each element has a type and either an id or a name
# You needn't specify app= or namespace= together with reference=,
# serialized= or urlsafe=, but if you do, their values must match
# what is already in the reference.
ref_app = reference.app()
if app is not None:
if app != ref_app:
raise RuntimeError('Key reference constructed uses a different app %r '
'than the one specified %r' %
(ref_app, app))
ref_namespace = reference.name_space()
if namespace is not None:
if namespace != ref_namespace:
raise RuntimeError('Key reference constructed uses a different '
'namespace %r than the one specified %r' %
(ref_namespace, namespace))
return (reference, tuple(pairs), ref_app, ref_namespace) | python | 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 reference on non-Key class; '
'received %r' % cls)
if (bool(pairs) + bool(flat) + bool(reference) + bool(serialized) +
bool(urlsafe) + bool(parent)) != 1:
raise TypeError('Cannot construct Key reference from incompatible '
'keyword arguments.')
if urlsafe:
serialized = _DecodeUrlSafe(urlsafe)
if serialized:
reference = _ReferenceFromSerialized(serialized)
if reference:
reference = _ReferenceFromReference(reference)
pairs = []
elem = None
path = reference.path()
for elem in path.element_list():
kind = elem.type()
if elem.has_id():
id_or_name = elem.id()
else:
id_or_name = elem.name()
if not id_or_name:
id_or_name = None
tup = (kind, id_or_name)
pairs.append(tup)
if elem is None:
raise RuntimeError('Key reference has no path or elements (%r, %r, %r).'
% (urlsafe, serialized, str(reference)))
# TODO: ensure that each element has a type and either an id or a name
# You needn't specify app= or namespace= together with reference=,
# serialized= or urlsafe=, but if you do, their values must match
# what is already in the reference.
ref_app = reference.app()
if app is not None:
if app != ref_app:
raise RuntimeError('Key reference constructed uses a different app %r '
'than the one specified %r' %
(ref_app, app))
ref_namespace = reference.name_space()
if namespace is not None:
if namespace != ref_namespace:
raise RuntimeError('Key reference constructed uses a different '
'namespace %r than the one specified %r' %
(ref_namespace, namespace))
return (reference, tuple(pairs), ref_app, ref_namespace) | [
"def",
"_parse_from_ref",
"(",
"cls",
",",
"pairs",
"=",
"None",
",",
"flat",
"=",
"None",
",",
"reference",
"=",
"None",
",",
"serialized",
"=",
"None",
",",
"urlsafe",
"=",
"None",
",",
"app",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"not",
"Key",
":",
"raise",
"TypeError",
"(",
"'Cannot construct Key reference on non-Key class; '",
"'received %r'",
"%",
"cls",
")",
"if",
"(",
"bool",
"(",
"pairs",
")",
"+",
"bool",
"(",
"flat",
")",
"+",
"bool",
"(",
"reference",
")",
"+",
"bool",
"(",
"serialized",
")",
"+",
"bool",
"(",
"urlsafe",
")",
"+",
"bool",
"(",
"parent",
")",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"'Cannot construct Key reference from incompatible '",
"'keyword arguments.'",
")",
"if",
"urlsafe",
":",
"serialized",
"=",
"_DecodeUrlSafe",
"(",
"urlsafe",
")",
"if",
"serialized",
":",
"reference",
"=",
"_ReferenceFromSerialized",
"(",
"serialized",
")",
"if",
"reference",
":",
"reference",
"=",
"_ReferenceFromReference",
"(",
"reference",
")",
"pairs",
"=",
"[",
"]",
"elem",
"=",
"None",
"path",
"=",
"reference",
".",
"path",
"(",
")",
"for",
"elem",
"in",
"path",
".",
"element_list",
"(",
")",
":",
"kind",
"=",
"elem",
".",
"type",
"(",
")",
"if",
"elem",
".",
"has_id",
"(",
")",
":",
"id_or_name",
"=",
"elem",
".",
"id",
"(",
")",
"else",
":",
"id_or_name",
"=",
"elem",
".",
"name",
"(",
")",
"if",
"not",
"id_or_name",
":",
"id_or_name",
"=",
"None",
"tup",
"=",
"(",
"kind",
",",
"id_or_name",
")",
"pairs",
".",
"append",
"(",
"tup",
")",
"if",
"elem",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Key reference has no path or elements (%r, %r, %r).'",
"%",
"(",
"urlsafe",
",",
"serialized",
",",
"str",
"(",
"reference",
")",
")",
")",
"# TODO: ensure that each element has a type and either an id or a name",
"# You needn't specify app= or namespace= together with reference=,",
"# serialized= or urlsafe=, but if you do, their values must match",
"# what is already in the reference.",
"ref_app",
"=",
"reference",
".",
"app",
"(",
")",
"if",
"app",
"is",
"not",
"None",
":",
"if",
"app",
"!=",
"ref_app",
":",
"raise",
"RuntimeError",
"(",
"'Key reference constructed uses a different app %r '",
"'than the one specified %r'",
"%",
"(",
"ref_app",
",",
"app",
")",
")",
"ref_namespace",
"=",
"reference",
".",
"name_space",
"(",
")",
"if",
"namespace",
"is",
"not",
"None",
":",
"if",
"namespace",
"!=",
"ref_namespace",
":",
"raise",
"RuntimeError",
"(",
"'Key reference constructed uses a different '",
"'namespace %r than the one specified %r'",
"%",
"(",
"ref_namespace",
",",
"namespace",
")",
")",
"return",
"(",
"reference",
",",
"tuple",
"(",
"pairs",
")",
",",
"ref_app",
",",
"ref_namespace",
")"
] | Construct a Reference; the signature is the same as for Key. | [
"Construct",
"a",
"Reference",
";",
"the",
"signature",
"is",
"the",
"same",
"as",
"for",
"Key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L304-L353 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.parent | 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) | python | 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",
"parent",
"(",
"self",
")",
":",
"pairs",
"=",
"self",
".",
"__pairs",
"if",
"len",
"(",
"pairs",
")",
"<=",
"1",
":",
"return",
"None",
"return",
"Key",
"(",
"pairs",
"=",
"pairs",
"[",
":",
"-",
"1",
"]",
",",
"app",
"=",
"self",
".",
"__app",
",",
"namespace",
"=",
"self",
".",
"__namespace",
")"
] | Return a Key constructed from all but the last (kind, id) pairs.
If there is only one (kind, id) pair, return None. | [
"Return",
"a",
"Key",
"constructed",
"from",
"all",
"but",
"the",
"last",
"(",
"kind",
"id",
")",
"pairs",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L460-L468 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.string_id | 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 | python | 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",
"string_id",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"id",
"(",
")",
"if",
"not",
"isinstance",
"(",
"id",
",",
"basestring",
")",
":",
"id",
"=",
"None",
"return",
"id"
] | 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",
"string",
"id",
"in",
"the",
"last",
"(",
"kind",
"id",
")",
"pair",
"if",
"any",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L493-L502 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.integer_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 | python | 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",
"integer_id",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"id",
"(",
")",
"if",
"not",
"isinstance",
"(",
"id",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"id",
"=",
"None",
"return",
"id"
] | 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. | [
"Return",
"the",
"integer",
"id",
"in",
"the",
"last",
"(",
"kind",
"id",
")",
"pair",
"if",
"any",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L504-L513 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.flat | 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) | python | 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) | [
"def",
"flat",
"(",
"self",
")",
":",
"flat",
"=",
"[",
"]",
"for",
"kind",
",",
"id",
"in",
"self",
".",
"__pairs",
":",
"flat",
".",
"append",
"(",
"kind",
")",
"flat",
".",
"append",
"(",
"id",
")",
"return",
"tuple",
"(",
"flat",
")"
] | Return a tuple of alternating kind and id values. | [
"Return",
"a",
"tuple",
"of",
"alternating",
"kind",
"and",
"id",
"values",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L519-L525 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.reference | def reference(self):
"""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.
"""
if self.__reference is None:
self.__reference = _ConstructReference(self.__class__,
pairs=self.__pairs,
app=self.__app,
namespace=self.__namespace)
return self.__reference | python | def reference(self):
"""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.
"""
if self.__reference is None:
self.__reference = _ConstructReference(self.__class__,
pairs=self.__pairs,
app=self.__app,
namespace=self.__namespace)
return self.__reference | [
"def",
"reference",
"(",
"self",
")",
":",
"if",
"self",
".",
"__reference",
"is",
"None",
":",
"self",
".",
"__reference",
"=",
"_ConstructReference",
"(",
"self",
".",
"__class__",
",",
"pairs",
"=",
"self",
".",
"__pairs",
",",
"app",
"=",
"self",
".",
"__app",
",",
"namespace",
"=",
"self",
".",
"__namespace",
")",
"return",
"self",
".",
"__reference"
] | 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. | [
"Return",
"the",
"Reference",
"object",
"for",
"this",
"Key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L534-L547 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.urlsafe | def urlsafe(self):
"""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.
"""
# This is 3-4x faster than urlsafe_b64decode()
urlsafe = base64.b64encode(self.reference().Encode())
return urlsafe.rstrip('=').replace('+', '-').replace('/', '_') | python | def urlsafe(self):
"""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.
"""
# This is 3-4x faster than urlsafe_b64decode()
urlsafe = base64.b64encode(self.reference().Encode())
return urlsafe.rstrip('=').replace('+', '-').replace('/', '_') | [
"def",
"urlsafe",
"(",
"self",
")",
":",
"# This is 3-4x faster than urlsafe_b64decode()",
"urlsafe",
"=",
"base64",
".",
"b64encode",
"(",
"self",
".",
"reference",
"(",
")",
".",
"Encode",
"(",
")",
")",
"return",
"urlsafe",
".",
"rstrip",
"(",
"'='",
")",
".",
"replace",
"(",
"'+'",
",",
"'-'",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")"
] | 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. | [
"Return",
"a",
"url",
"-",
"safe",
"string",
"encoding",
"this",
"Key",
"s",
"Reference",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L553-L562 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.get_async | 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 returned, and the
Future's eventual return result be None.
"""
from . import model, tasklets
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_get_hook(self)
fut = ctx.get(self, **ctx_options)
if cls:
post_hook = cls._post_get_hook
if not cls._is_default_hook(model.Model._default_post_get_hook,
post_hook):
fut.add_immediate_callback(post_hook, self, fut)
return fut | python | 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 returned, and the
Future's eventual return result be None.
"""
from . import model, tasklets
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_get_hook(self)
fut = ctx.get(self, **ctx_options)
if cls:
post_hook = cls._post_get_hook
if not cls._is_default_hook(model.Model._default_post_get_hook,
post_hook):
fut.add_immediate_callback(post_hook, self, fut)
return fut | [
"def",
"get_async",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
":",
"from",
".",
"import",
"model",
",",
"tasklets",
"ctx",
"=",
"tasklets",
".",
"get_context",
"(",
")",
"cls",
"=",
"model",
".",
"Model",
".",
"_kind_map",
".",
"get",
"(",
"self",
".",
"kind",
"(",
")",
")",
"if",
"cls",
":",
"cls",
".",
"_pre_get_hook",
"(",
"self",
")",
"fut",
"=",
"ctx",
".",
"get",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
"if",
"cls",
":",
"post_hook",
"=",
"cls",
".",
"_post_get_hook",
"if",
"not",
"cls",
".",
"_is_default_hook",
"(",
"model",
".",
"Model",
".",
"_default_post_get_hook",
",",
"post_hook",
")",
":",
"fut",
".",
"add_immediate_callback",
"(",
"post_hook",
",",
"self",
",",
"fut",
")",
"return",
"fut"
] | 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. | [
"Return",
"a",
"Future",
"whose",
"result",
"is",
"the",
"entity",
"for",
"this",
"Key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L574-L591 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/key.py | Key.delete_async | def delete_async(self, **ctx_options):
"""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).
"""
from . import tasklets, model
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_delete_hook(self)
fut = ctx.delete(self, **ctx_options)
if cls:
post_hook = cls._post_delete_hook
if not cls._is_default_hook(model.Model._default_post_delete_hook,
post_hook):
fut.add_immediate_callback(post_hook, self, fut)
return fut | python | def delete_async(self, **ctx_options):
"""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).
"""
from . import tasklets, model
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_delete_hook(self)
fut = ctx.delete(self, **ctx_options)
if cls:
post_hook = cls._post_delete_hook
if not cls._is_default_hook(model.Model._default_post_delete_hook,
post_hook):
fut.add_immediate_callback(post_hook, self, fut)
return fut | [
"def",
"delete_async",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
":",
"from",
".",
"import",
"tasklets",
",",
"model",
"ctx",
"=",
"tasklets",
".",
"get_context",
"(",
")",
"cls",
"=",
"model",
".",
"Model",
".",
"_kind_map",
".",
"get",
"(",
"self",
".",
"kind",
"(",
")",
")",
"if",
"cls",
":",
"cls",
".",
"_pre_delete_hook",
"(",
"self",
")",
"fut",
"=",
"ctx",
".",
"delete",
"(",
"self",
",",
"*",
"*",
"ctx_options",
")",
"if",
"cls",
":",
"post_hook",
"=",
"cls",
".",
"_post_delete_hook",
"if",
"not",
"cls",
".",
"_is_default_hook",
"(",
"model",
".",
"Model",
".",
"_default_post_delete_hook",
",",
"post_hook",
")",
":",
"fut",
".",
"add_immediate_callback",
"(",
"post_hook",
",",
"self",
",",
"fut",
")",
"return",
"fut"
] | 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). | [
"Schedule",
"deletion",
"of",
"the",
"entity",
"for",
"this",
"Key",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/key.py#L600-L619 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | add_flow_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):
raise TypeError('Expected an Exception subclass, got %r' % (exc,))
as_set = set(_flow_exceptions)
as_set.add(exc)
_flow_exceptions = tuple(as_set) | python | 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):
raise TypeError('Expected an Exception subclass, got %r' % (exc,))
as_set = set(_flow_exceptions)
as_set.add(exc)
_flow_exceptions = tuple(as_set) | [
"def",
"add_flow_exception",
"(",
"exc",
")",
":",
"global",
"_flow_exceptions",
"if",
"not",
"isinstance",
"(",
"exc",
",",
"type",
")",
"or",
"not",
"issubclass",
"(",
"exc",
",",
"Exception",
")",
":",
"raise",
"TypeError",
"(",
"'Expected an Exception subclass, got %r'",
"%",
"(",
"exc",
",",
")",
")",
"as_set",
"=",
"set",
"(",
"_flow_exceptions",
")",
"as_set",
".",
"add",
"(",
"exc",
")",
"_flow_exceptions",
"=",
"tuple",
"(",
"as_set",
")"
] | Add an exception that should not be logged.
The argument must be a subclass of Exception. | [
"Add",
"an",
"exception",
"that",
"should",
"not",
"be",
"logged",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L201-L211 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | _init_flow_exceptions | 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_exceptions = ()
add_flow_exception(datastore_errors.Rollback)
try:
from webob import exc
except ImportError:
pass
else:
add_flow_exception(exc.HTTPException) | python | 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_exceptions = ()
add_flow_exception(datastore_errors.Rollback)
try:
from webob import exc
except ImportError:
pass
else:
add_flow_exception(exc.HTTPException) | [
"def",
"_init_flow_exceptions",
"(",
")",
":",
"global",
"_flow_exceptions",
"_flow_exceptions",
"=",
"(",
")",
"add_flow_exception",
"(",
"datastore_errors",
".",
"Rollback",
")",
"try",
":",
"from",
"webob",
"import",
"exc",
"except",
"ImportError",
":",
"pass",
"else",
":",
"add_flow_exception",
"(",
"exc",
".",
"HTTPException",
")"
] | Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported. | [
"Internal",
"helper",
"to",
"initialize",
"_flow_exceptions",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L214-L227 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | sleep | 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)
return fut | python | 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)
return fut | [
"def",
"sleep",
"(",
"dt",
")",
":",
"fut",
"=",
"Future",
"(",
"'sleep(%.3f)'",
"%",
"dt",
")",
"eventloop",
".",
"queue_call",
"(",
"dt",
",",
"fut",
".",
"set_result",
",",
"None",
")",
"return",
"fut"
] | Public function to sleep some time.
Example:
yield tasklets.sleep(0.5) # Sleep for half a sec. | [
"Public",
"function",
"to",
"sleep",
"some",
"time",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L536-L544 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | _transfer_result | 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()
fut2.set_result(val) | python | 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()
fut2.set_result(val) | [
"def",
"_transfer_result",
"(",
"fut1",
",",
"fut2",
")",
":",
"exc",
"=",
"fut1",
".",
"get_exception",
"(",
")",
"if",
"exc",
"is",
"not",
"None",
":",
"tb",
"=",
"fut1",
".",
"get_traceback",
"(",
")",
"fut2",
".",
"set_exception",
"(",
"exc",
",",
"tb",
")",
"else",
":",
"val",
"=",
"fut1",
".",
"get_result",
"(",
")",
"fut2",
".",
"set_result",
"(",
"val",
")"
] | Helper to transfer result or errors from one Future to another. | [
"Helper",
"to",
"transfer",
"result",
"or",
"errors",
"from",
"one",
"Future",
"to",
"another",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L897-L905 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | synctasklet | def synctasklet(func):
"""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).
"""
taskletfunc = tasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def synctasklet_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
return taskletfunc(*args, **kwds).get_result()
return synctasklet_wrapper | python | def synctasklet(func):
"""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).
"""
taskletfunc = tasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def synctasklet_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
return taskletfunc(*args, **kwds).get_result()
return synctasklet_wrapper | [
"def",
"synctasklet",
"(",
"func",
")",
":",
"taskletfunc",
"=",
"tasklet",
"(",
"func",
")",
"# wrap at declaration time.",
"@",
"utils",
".",
"wrapping",
"(",
"func",
")",
"def",
"synctasklet_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# pylint: disable=invalid-name",
"__ndb_debug__",
"=",
"utils",
".",
"func_info",
"(",
"func",
")",
"return",
"taskletfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
".",
"get_result",
"(",
")",
"return",
"synctasklet_wrapper"
] | 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). | [
"Decorator",
"to",
"run",
"a",
"function",
"as",
"a",
"tasklet",
"when",
"called",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L1074-L1088 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | toplevel | 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 view functions.
"""
synctaskletfunc = synctasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def add_context_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
_state.clear_all_pending()
# Create and install a new context.
ctx = make_default_context()
try:
set_context(ctx)
return synctaskletfunc(*args, **kwds)
finally:
set_context(None)
ctx.flush().check_success()
eventloop.run() # Ensure writes are flushed, etc.
return add_context_wrapper | python | 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 view functions.
"""
synctaskletfunc = synctasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def add_context_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
_state.clear_all_pending()
# Create and install a new context.
ctx = make_default_context()
try:
set_context(ctx)
return synctaskletfunc(*args, **kwds)
finally:
set_context(None)
ctx.flush().check_success()
eventloop.run() # Ensure writes are flushed, etc.
return add_context_wrapper | [
"def",
"toplevel",
"(",
"func",
")",
":",
"synctaskletfunc",
"=",
"synctasklet",
"(",
"func",
")",
"# wrap at declaration time.",
"@",
"utils",
".",
"wrapping",
"(",
"func",
")",
"def",
"add_context_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# pylint: disable=invalid-name",
"__ndb_debug__",
"=",
"utils",
".",
"func_info",
"(",
"func",
")",
"_state",
".",
"clear_all_pending",
"(",
")",
"# Create and install a new context.",
"ctx",
"=",
"make_default_context",
"(",
")",
"try",
":",
"set_context",
"(",
"ctx",
")",
"return",
"synctaskletfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"finally",
":",
"set_context",
"(",
"None",
")",
"ctx",
".",
"flush",
"(",
")",
".",
"check_success",
"(",
")",
"eventloop",
".",
"run",
"(",
")",
"# Ensure writes are flushed, etc.",
"return",
"add_context_wrapper"
] | A sync tasklet that sets a fresh default Context.
Use this for toplevel view functions such as
webapp.RequestHandler.get() or Django view functions. | [
"A",
"sync",
"tasklet",
"that",
"sets",
"a",
"fresh",
"default",
"Context",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L1091-L1113 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | _make_cloud_datastore_context | def _make_cloud_datastore_context(app_id, external_app_ids=()):
"""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 may be referenced by data in your
application. For example, if you are connected to s~my-app and store keys
for s~my-other-app, you should include s~my-other-app in the external_apps
list.
Returns:
An ndb.Context that can connect to a Remote Cloud Datastore. You can use
this context by passing it to ndb.set_context.
"""
from . import model # Late import to deal with circular imports.
# Late import since it might not exist.
if not datastore_pbs._CLOUD_DATASTORE_ENABLED:
raise datastore_errors.BadArgumentError(
datastore_pbs.MISSING_CLOUD_DATASTORE_MESSAGE)
import googledatastore
try:
from google.appengine.datastore import cloud_datastore_v1_remote_stub
except ImportError:
from google3.apphosting.datastore import cloud_datastore_v1_remote_stub
current_app_id = os.environ.get('APPLICATION_ID', None)
if current_app_id and current_app_id != app_id:
# TODO(pcostello): We should support this so users can connect to different
# applications.
raise ValueError('Cannot create a Cloud Datastore context that connects '
'to an application (%s) that differs from the application '
'already connected to (%s).' % (app_id, current_app_id))
os.environ['APPLICATION_ID'] = app_id
id_resolver = datastore_pbs.IdResolver((app_id,) + tuple(external_app_ids))
project_id = id_resolver.resolve_project_id(app_id)
endpoint = googledatastore.helper.get_project_endpoint_from_env(project_id)
datastore = googledatastore.Datastore(
project_endpoint=endpoint,
credentials=googledatastore.helper.get_credentials_from_env())
conn = model.make_connection(_api_version=datastore_rpc._CLOUD_DATASTORE_V1,
_id_resolver=id_resolver)
# If necessary, install the stubs
try:
stub = cloud_datastore_v1_remote_stub.CloudDatastoreV1RemoteStub(datastore)
apiproxy_stub_map.apiproxy.RegisterStub(datastore_rpc._CLOUD_DATASTORE_V1,
stub)
except:
pass # The stub is already installed.
# TODO(pcostello): Ensure the current stub is connected to the right project.
# Install a memcache and taskqueue stub which throws on everything.
try:
apiproxy_stub_map.apiproxy.RegisterStub('memcache', _ThrowingStub())
except:
pass # The stub is already installed.
try:
apiproxy_stub_map.apiproxy.RegisterStub('taskqueue', _ThrowingStub())
except:
pass # The stub is already installed.
return make_context(conn=conn) | python | def _make_cloud_datastore_context(app_id, external_app_ids=()):
"""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 may be referenced by data in your
application. For example, if you are connected to s~my-app and store keys
for s~my-other-app, you should include s~my-other-app in the external_apps
list.
Returns:
An ndb.Context that can connect to a Remote Cloud Datastore. You can use
this context by passing it to ndb.set_context.
"""
from . import model # Late import to deal with circular imports.
# Late import since it might not exist.
if not datastore_pbs._CLOUD_DATASTORE_ENABLED:
raise datastore_errors.BadArgumentError(
datastore_pbs.MISSING_CLOUD_DATASTORE_MESSAGE)
import googledatastore
try:
from google.appengine.datastore import cloud_datastore_v1_remote_stub
except ImportError:
from google3.apphosting.datastore import cloud_datastore_v1_remote_stub
current_app_id = os.environ.get('APPLICATION_ID', None)
if current_app_id and current_app_id != app_id:
# TODO(pcostello): We should support this so users can connect to different
# applications.
raise ValueError('Cannot create a Cloud Datastore context that connects '
'to an application (%s) that differs from the application '
'already connected to (%s).' % (app_id, current_app_id))
os.environ['APPLICATION_ID'] = app_id
id_resolver = datastore_pbs.IdResolver((app_id,) + tuple(external_app_ids))
project_id = id_resolver.resolve_project_id(app_id)
endpoint = googledatastore.helper.get_project_endpoint_from_env(project_id)
datastore = googledatastore.Datastore(
project_endpoint=endpoint,
credentials=googledatastore.helper.get_credentials_from_env())
conn = model.make_connection(_api_version=datastore_rpc._CLOUD_DATASTORE_V1,
_id_resolver=id_resolver)
# If necessary, install the stubs
try:
stub = cloud_datastore_v1_remote_stub.CloudDatastoreV1RemoteStub(datastore)
apiproxy_stub_map.apiproxy.RegisterStub(datastore_rpc._CLOUD_DATASTORE_V1,
stub)
except:
pass # The stub is already installed.
# TODO(pcostello): Ensure the current stub is connected to the right project.
# Install a memcache and taskqueue stub which throws on everything.
try:
apiproxy_stub_map.apiproxy.RegisterStub('memcache', _ThrowingStub())
except:
pass # The stub is already installed.
try:
apiproxy_stub_map.apiproxy.RegisterStub('taskqueue', _ThrowingStub())
except:
pass # The stub is already installed.
return make_context(conn=conn) | [
"def",
"_make_cloud_datastore_context",
"(",
"app_id",
",",
"external_app_ids",
"=",
"(",
")",
")",
":",
"from",
".",
"import",
"model",
"# Late import to deal with circular imports.",
"# Late import since it might not exist.",
"if",
"not",
"datastore_pbs",
".",
"_CLOUD_DATASTORE_ENABLED",
":",
"raise",
"datastore_errors",
".",
"BadArgumentError",
"(",
"datastore_pbs",
".",
"MISSING_CLOUD_DATASTORE_MESSAGE",
")",
"import",
"googledatastore",
"try",
":",
"from",
"google",
".",
"appengine",
".",
"datastore",
"import",
"cloud_datastore_v1_remote_stub",
"except",
"ImportError",
":",
"from",
"google3",
".",
"apphosting",
".",
"datastore",
"import",
"cloud_datastore_v1_remote_stub",
"current_app_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'APPLICATION_ID'",
",",
"None",
")",
"if",
"current_app_id",
"and",
"current_app_id",
"!=",
"app_id",
":",
"# TODO(pcostello): We should support this so users can connect to different",
"# applications.",
"raise",
"ValueError",
"(",
"'Cannot create a Cloud Datastore context that connects '",
"'to an application (%s) that differs from the application '",
"'already connected to (%s).'",
"%",
"(",
"app_id",
",",
"current_app_id",
")",
")",
"os",
".",
"environ",
"[",
"'APPLICATION_ID'",
"]",
"=",
"app_id",
"id_resolver",
"=",
"datastore_pbs",
".",
"IdResolver",
"(",
"(",
"app_id",
",",
")",
"+",
"tuple",
"(",
"external_app_ids",
")",
")",
"project_id",
"=",
"id_resolver",
".",
"resolve_project_id",
"(",
"app_id",
")",
"endpoint",
"=",
"googledatastore",
".",
"helper",
".",
"get_project_endpoint_from_env",
"(",
"project_id",
")",
"datastore",
"=",
"googledatastore",
".",
"Datastore",
"(",
"project_endpoint",
"=",
"endpoint",
",",
"credentials",
"=",
"googledatastore",
".",
"helper",
".",
"get_credentials_from_env",
"(",
")",
")",
"conn",
"=",
"model",
".",
"make_connection",
"(",
"_api_version",
"=",
"datastore_rpc",
".",
"_CLOUD_DATASTORE_V1",
",",
"_id_resolver",
"=",
"id_resolver",
")",
"# If necessary, install the stubs",
"try",
":",
"stub",
"=",
"cloud_datastore_v1_remote_stub",
".",
"CloudDatastoreV1RemoteStub",
"(",
"datastore",
")",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"datastore_rpc",
".",
"_CLOUD_DATASTORE_V1",
",",
"stub",
")",
"except",
":",
"pass",
"# The stub is already installed.",
"# TODO(pcostello): Ensure the current stub is connected to the right project.",
"# Install a memcache and taskqueue stub which throws on everything.",
"try",
":",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"'memcache'",
",",
"_ThrowingStub",
"(",
")",
")",
"except",
":",
"pass",
"# The stub is already installed.",
"try",
":",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"'taskqueue'",
",",
"_ThrowingStub",
"(",
")",
")",
"except",
":",
"pass",
"# The stub is already installed.",
"return",
"make_context",
"(",
"conn",
"=",
"conn",
")"
] | 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 may be referenced by data in your
application. For example, if you are connected to s~my-app and store keys
for s~my-other-app, you should include s~my-other-app in the external_apps
list.
Returns:
An ndb.Context that can connect to a Remote Cloud Datastore. You can use
this context by passing it to ndb.set_context. | [
"Creates",
"a",
"new",
"context",
"to",
"connect",
"to",
"a",
"remote",
"Cloud",
"Datastore",
"instance",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L1183-L1249 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | _analyze_indexed_fields | def _analyze_indexed_fields(indexed_fields):
"""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 names. For each undotted name in
the argument, the dict contains that undotted name as a key with
None as a value. For each dotted name in the argument, the dict
contains the first component as a key with a list of remainders as
values.
Example:
If the argument is ['foo.bar.baz', 'bar', 'foo.bletch'], the return
value is {'foo': ['bar.baz', 'bletch'], 'bar': None}.
Raises:
TypeError if an argument is not a string.
ValueError for duplicate arguments and for conflicting arguments
(when an undotted name also appears as the first component of
a dotted name).
"""
result = {}
for field_name in indexed_fields:
if not isinstance(field_name, basestring):
raise TypeError('Field names must be strings; got %r' % (field_name,))
if '.' not in field_name:
if field_name in result:
raise ValueError('Duplicate field name %s' % field_name)
result[field_name] = None
else:
head, tail = field_name.split('.', 1)
if head not in result:
result[head] = [tail]
elif result[head] is None:
raise ValueError('Field name %s conflicts with ancestor %s' %
(field_name, head))
else:
result[head].append(tail)
return result | python | def _analyze_indexed_fields(indexed_fields):
"""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 names. For each undotted name in
the argument, the dict contains that undotted name as a key with
None as a value. For each dotted name in the argument, the dict
contains the first component as a key with a list of remainders as
values.
Example:
If the argument is ['foo.bar.baz', 'bar', 'foo.bletch'], the return
value is {'foo': ['bar.baz', 'bletch'], 'bar': None}.
Raises:
TypeError if an argument is not a string.
ValueError for duplicate arguments and for conflicting arguments
(when an undotted name also appears as the first component of
a dotted name).
"""
result = {}
for field_name in indexed_fields:
if not isinstance(field_name, basestring):
raise TypeError('Field names must be strings; got %r' % (field_name,))
if '.' not in field_name:
if field_name in result:
raise ValueError('Duplicate field name %s' % field_name)
result[field_name] = None
else:
head, tail = field_name.split('.', 1)
if head not in result:
result[head] = [tail]
elif result[head] is None:
raise ValueError('Field name %s conflicts with ancestor %s' %
(field_name, head))
else:
result[head].append(tail)
return result | [
"def",
"_analyze_indexed_fields",
"(",
"indexed_fields",
")",
":",
"result",
"=",
"{",
"}",
"for",
"field_name",
"in",
"indexed_fields",
":",
"if",
"not",
"isinstance",
"(",
"field_name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'Field names must be strings; got %r'",
"%",
"(",
"field_name",
",",
")",
")",
"if",
"'.'",
"not",
"in",
"field_name",
":",
"if",
"field_name",
"in",
"result",
":",
"raise",
"ValueError",
"(",
"'Duplicate field name %s'",
"%",
"field_name",
")",
"result",
"[",
"field_name",
"]",
"=",
"None",
"else",
":",
"head",
",",
"tail",
"=",
"field_name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"if",
"head",
"not",
"in",
"result",
":",
"result",
"[",
"head",
"]",
"=",
"[",
"tail",
"]",
"elif",
"result",
"[",
"head",
"]",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Field name %s conflicts with ancestor %s'",
"%",
"(",
"field_name",
",",
"head",
")",
")",
"else",
":",
"result",
"[",
"head",
"]",
".",
"append",
"(",
"tail",
")",
"return",
"result"
] | 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 names. For each undotted name in
the argument, the dict contains that undotted name as a key with
None as a value. For each dotted name in the argument, the dict
contains the first component as a key with a list of remainders as
values.
Example:
If the argument is ['foo.bar.baz', 'bar', 'foo.bletch'], the return
value is {'foo': ['bar.baz', 'bletch'], 'bar': None}.
Raises:
TypeError if an argument is not a string.
ValueError for duplicate arguments and for conflicting arguments
(when an undotted name also appears as the first component of
a dotted name). | [
"Internal",
"helper",
"to",
"check",
"a",
"list",
"of",
"indexed",
"fields",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L201-L245 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | _make_model_class | def _make_model_class(message_type, indexed_fields, **props):
"""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
message_type whose field name is listed in indexed_fields, plus
the properties specified by the **props arguments. For dotted
field names, a StructuredProperty is generated using a Model
subclass created by a recursive call.
Raises:
Whatever _analyze_indexed_fields() raises.
ValueError if a field name conflicts with a name in **props.
ValueError if a field name is not valid field of message_type.
ValueError if an undotted field name designates a MessageField.
"""
analyzed = _analyze_indexed_fields(indexed_fields)
for field_name, sub_fields in analyzed.iteritems():
if field_name in props:
raise ValueError('field name %s is reserved' % field_name)
try:
field = message_type.field_by_name(field_name)
except KeyError:
raise ValueError('Message type %s has no field named %s' %
(message_type.__name__, field_name))
if isinstance(field, messages.MessageField):
if not sub_fields:
raise ValueError(
'MessageField %s cannot be indexed, only sub-fields' % field_name)
sub_model_class = _make_model_class(field.type, sub_fields)
prop = model.StructuredProperty(sub_model_class, field_name,
repeated=field.repeated)
else:
if sub_fields is not None:
raise ValueError(
'Unstructured field %s cannot have indexed sub-fields' % field_name)
if isinstance(field, messages.EnumField):
prop = EnumProperty(field.type, field_name, repeated=field.repeated)
elif isinstance(field, messages.BytesField):
prop = model.BlobProperty(field_name,
repeated=field.repeated, indexed=True)
else:
# IntegerField, FloatField, BooleanField, StringField.
prop = model.GenericProperty(field_name, repeated=field.repeated)
props[field_name] = prop
return model.MetaModel('_%s__Model' % message_type.__name__,
(model.Model,), props) | python | def _make_model_class(message_type, indexed_fields, **props):
"""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
message_type whose field name is listed in indexed_fields, plus
the properties specified by the **props arguments. For dotted
field names, a StructuredProperty is generated using a Model
subclass created by a recursive call.
Raises:
Whatever _analyze_indexed_fields() raises.
ValueError if a field name conflicts with a name in **props.
ValueError if a field name is not valid field of message_type.
ValueError if an undotted field name designates a MessageField.
"""
analyzed = _analyze_indexed_fields(indexed_fields)
for field_name, sub_fields in analyzed.iteritems():
if field_name in props:
raise ValueError('field name %s is reserved' % field_name)
try:
field = message_type.field_by_name(field_name)
except KeyError:
raise ValueError('Message type %s has no field named %s' %
(message_type.__name__, field_name))
if isinstance(field, messages.MessageField):
if not sub_fields:
raise ValueError(
'MessageField %s cannot be indexed, only sub-fields' % field_name)
sub_model_class = _make_model_class(field.type, sub_fields)
prop = model.StructuredProperty(sub_model_class, field_name,
repeated=field.repeated)
else:
if sub_fields is not None:
raise ValueError(
'Unstructured field %s cannot have indexed sub-fields' % field_name)
if isinstance(field, messages.EnumField):
prop = EnumProperty(field.type, field_name, repeated=field.repeated)
elif isinstance(field, messages.BytesField):
prop = model.BlobProperty(field_name,
repeated=field.repeated, indexed=True)
else:
# IntegerField, FloatField, BooleanField, StringField.
prop = model.GenericProperty(field_name, repeated=field.repeated)
props[field_name] = prop
return model.MetaModel('_%s__Model' % message_type.__name__,
(model.Model,), props) | [
"def",
"_make_model_class",
"(",
"message_type",
",",
"indexed_fields",
",",
"*",
"*",
"props",
")",
":",
"analyzed",
"=",
"_analyze_indexed_fields",
"(",
"indexed_fields",
")",
"for",
"field_name",
",",
"sub_fields",
"in",
"analyzed",
".",
"iteritems",
"(",
")",
":",
"if",
"field_name",
"in",
"props",
":",
"raise",
"ValueError",
"(",
"'field name %s is reserved'",
"%",
"field_name",
")",
"try",
":",
"field",
"=",
"message_type",
".",
"field_by_name",
"(",
"field_name",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Message type %s has no field named %s'",
"%",
"(",
"message_type",
".",
"__name__",
",",
"field_name",
")",
")",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"MessageField",
")",
":",
"if",
"not",
"sub_fields",
":",
"raise",
"ValueError",
"(",
"'MessageField %s cannot be indexed, only sub-fields'",
"%",
"field_name",
")",
"sub_model_class",
"=",
"_make_model_class",
"(",
"field",
".",
"type",
",",
"sub_fields",
")",
"prop",
"=",
"model",
".",
"StructuredProperty",
"(",
"sub_model_class",
",",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"else",
":",
"if",
"sub_fields",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Unstructured field %s cannot have indexed sub-fields'",
"%",
"field_name",
")",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"EnumField",
")",
":",
"prop",
"=",
"EnumProperty",
"(",
"field",
".",
"type",
",",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"elif",
"isinstance",
"(",
"field",
",",
"messages",
".",
"BytesField",
")",
":",
"prop",
"=",
"model",
".",
"BlobProperty",
"(",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
",",
"indexed",
"=",
"True",
")",
"else",
":",
"# IntegerField, FloatField, BooleanField, StringField.",
"prop",
"=",
"model",
".",
"GenericProperty",
"(",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"props",
"[",
"field_name",
"]",
"=",
"prop",
"return",
"model",
".",
"MetaModel",
"(",
"'_%s__Model'",
"%",
"message_type",
".",
"__name__",
",",
"(",
"model",
".",
"Model",
",",
")",
",",
"props",
")"
] | 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
message_type whose field name is listed in indexed_fields, plus
the properties specified by the **props arguments. For dotted
field names, a StructuredProperty is generated using a Model
subclass created by a recursive call.
Raises:
Whatever _analyze_indexed_fields() raises.
ValueError if a field name conflicts with a name in **props.
ValueError if a field name is not valid field of message_type.
ValueError if an undotted field name designates a MessageField. | [
"Construct",
"a",
"Model",
"subclass",
"corresponding",
"to",
"a",
"Message",
"subclass",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L248-L299 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | _message_to_entity | def _message_to_entity(msg, modelclass):
"""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.
"""
ent = modelclass()
for prop_name, prop in modelclass._properties.iteritems():
if prop._code_name == 'blob_': # TODO: Devise a cleaner test.
continue # That's taken care of later.
value = getattr(msg, prop_name)
if value is not None and isinstance(prop, model.StructuredProperty):
if prop._repeated:
value = [_message_to_entity(v, prop._modelclass) for v in value]
else:
value = _message_to_entity(value, prop._modelclass)
setattr(ent, prop_name, value)
return ent | python | def _message_to_entity(msg, modelclass):
"""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.
"""
ent = modelclass()
for prop_name, prop in modelclass._properties.iteritems():
if prop._code_name == 'blob_': # TODO: Devise a cleaner test.
continue # That's taken care of later.
value = getattr(msg, prop_name)
if value is not None and isinstance(prop, model.StructuredProperty):
if prop._repeated:
value = [_message_to_entity(v, prop._modelclass) for v in value]
else:
value = _message_to_entity(value, prop._modelclass)
setattr(ent, prop_name, value)
return ent | [
"def",
"_message_to_entity",
"(",
"msg",
",",
"modelclass",
")",
":",
"ent",
"=",
"modelclass",
"(",
")",
"for",
"prop_name",
",",
"prop",
"in",
"modelclass",
".",
"_properties",
".",
"iteritems",
"(",
")",
":",
"if",
"prop",
".",
"_code_name",
"==",
"'blob_'",
":",
"# TODO: Devise a cleaner test.",
"continue",
"# That's taken care of later.",
"value",
"=",
"getattr",
"(",
"msg",
",",
"prop_name",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"prop",
",",
"model",
".",
"StructuredProperty",
")",
":",
"if",
"prop",
".",
"_repeated",
":",
"value",
"=",
"[",
"_message_to_entity",
"(",
"v",
",",
"prop",
".",
"_modelclass",
")",
"for",
"v",
"in",
"value",
"]",
"else",
":",
"value",
"=",
"_message_to_entity",
"(",
"value",
",",
"prop",
".",
"_modelclass",
")",
"setattr",
"(",
"ent",
",",
"prop_name",
",",
"value",
")",
"return",
"ent"
] | 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. | [
"Recursive",
"helper",
"for",
"_to_base_type",
"()",
"to",
"convert",
"a",
"message",
"to",
"an",
"entity",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L396-L417 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | _projected_entity_to_message | def _projected_entity_to_message(ent, message_type):
"""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.
"""
msg = message_type()
analyzed = _analyze_indexed_fields(ent._projection)
for name, sublist in analyzed.iteritems():
prop = ent._properties[name]
val = prop._get_value(ent)
assert isinstance(prop, model.StructuredProperty) == bool(sublist)
if sublist:
field = message_type.field_by_name(name)
assert isinstance(field, messages.MessageField)
assert prop._repeated == field.repeated
if prop._repeated:
assert isinstance(val, list)
val = [_projected_entity_to_message(v, field.type) for v in val]
else:
assert isinstance(val, prop._modelclass)
val = _projected_entity_to_message(val, field.type)
setattr(msg, name, val)
return msg | python | def _projected_entity_to_message(ent, message_type):
"""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.
"""
msg = message_type()
analyzed = _analyze_indexed_fields(ent._projection)
for name, sublist in analyzed.iteritems():
prop = ent._properties[name]
val = prop._get_value(ent)
assert isinstance(prop, model.StructuredProperty) == bool(sublist)
if sublist:
field = message_type.field_by_name(name)
assert isinstance(field, messages.MessageField)
assert prop._repeated == field.repeated
if prop._repeated:
assert isinstance(val, list)
val = [_projected_entity_to_message(v, field.type) for v in val]
else:
assert isinstance(val, prop._modelclass)
val = _projected_entity_to_message(val, field.type)
setattr(msg, name, val)
return msg | [
"def",
"_projected_entity_to_message",
"(",
"ent",
",",
"message_type",
")",
":",
"msg",
"=",
"message_type",
"(",
")",
"analyzed",
"=",
"_analyze_indexed_fields",
"(",
"ent",
".",
"_projection",
")",
"for",
"name",
",",
"sublist",
"in",
"analyzed",
".",
"iteritems",
"(",
")",
":",
"prop",
"=",
"ent",
".",
"_properties",
"[",
"name",
"]",
"val",
"=",
"prop",
".",
"_get_value",
"(",
"ent",
")",
"assert",
"isinstance",
"(",
"prop",
",",
"model",
".",
"StructuredProperty",
")",
"==",
"bool",
"(",
"sublist",
")",
"if",
"sublist",
":",
"field",
"=",
"message_type",
".",
"field_by_name",
"(",
"name",
")",
"assert",
"isinstance",
"(",
"field",
",",
"messages",
".",
"MessageField",
")",
"assert",
"prop",
".",
"_repeated",
"==",
"field",
".",
"repeated",
"if",
"prop",
".",
"_repeated",
":",
"assert",
"isinstance",
"(",
"val",
",",
"list",
")",
"val",
"=",
"[",
"_projected_entity_to_message",
"(",
"v",
",",
"field",
".",
"type",
")",
"for",
"v",
"in",
"val",
"]",
"else",
":",
"assert",
"isinstance",
"(",
"val",
",",
"prop",
".",
"_modelclass",
")",
"val",
"=",
"_projected_entity_to_message",
"(",
"val",
",",
"field",
".",
"type",
")",
"setattr",
"(",
"msg",
",",
"name",
",",
"val",
")",
"return",
"msg"
] | 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. | [
"Recursive",
"helper",
"for",
"_from_base_type",
"()",
"to",
"convert",
"an",
"entity",
"to",
"a",
"message",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L420-L447 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | EnumProperty._validate | 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 TypeError('Expected a %s instance, got %r instead' %
(self._enum_type.__name__, value)) | python | 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 TypeError('Expected a %s instance, got %r instead' %
(self._enum_type.__name__, value)) | [
"def",
"_validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"_enum_type",
")",
":",
"raise",
"TypeError",
"(",
"'Expected a %s instance, got %r instead'",
"%",
"(",
"self",
".",
"_enum_type",
".",
"__name__",
",",
"value",
")",
")"
] | Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._enum_type. | [
"Validate",
"an",
"Enum",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L182-L190 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | MessageProperty._validate | 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 TypeError('Expected a %s instance for %s property',
self._message_type.__name__,
self._code_name or self._name) | python | 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 TypeError('Expected a %s instance for %s property',
self._message_type.__name__,
self._code_name or self._name) | [
"def",
"_validate",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"self",
".",
"_message_type",
")",
":",
"raise",
"TypeError",
"(",
"'Expected a %s instance for %s property'",
",",
"self",
".",
"_message_type",
".",
"__name__",
",",
"self",
".",
"_code_name",
"or",
"self",
".",
"_name",
")"
] | Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type. | [
"Validate",
"an",
"Enum",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L353-L362 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | MessageProperty._to_base_type | 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 | python | 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 | [
"def",
"_to_base_type",
"(",
"self",
",",
"msg",
")",
":",
"ent",
"=",
"_message_to_entity",
"(",
"msg",
",",
"self",
".",
"_modelclass",
")",
"ent",
".",
"blob_",
"=",
"self",
".",
"_protocol_impl",
".",
"encode_message",
"(",
"msg",
")",
"return",
"ent"
] | Convert a Message value to a Model instance (entity). | [
"Convert",
"a",
"Message",
"value",
"to",
"a",
"Model",
"instance",
"(",
"entity",
")",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L364-L368 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/msgprop.py | MessageProperty._from_base_type | 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)
blob = ent.blob_
if blob is not None:
protocol = self._protocol_impl
else:
# Perhaps it was written using a different protocol.
protocol = None
for name in _protocols_registry.names:
key = '__%s__' % name
if key in ent._values:
blob = ent._values[key]
if isinstance(blob, model._BaseValue):
blob = blob.b_val
protocol = _protocols_registry.lookup_by_name(name)
break
if blob is None or protocol is None:
return None # This will reveal the underlying dummy model.
msg = protocol.decode_message(self._message_type, blob)
return msg | python | 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)
blob = ent.blob_
if blob is not None:
protocol = self._protocol_impl
else:
# Perhaps it was written using a different protocol.
protocol = None
for name in _protocols_registry.names:
key = '__%s__' % name
if key in ent._values:
blob = ent._values[key]
if isinstance(blob, model._BaseValue):
blob = blob.b_val
protocol = _protocols_registry.lookup_by_name(name)
break
if blob is None or protocol is None:
return None # This will reveal the underlying dummy model.
msg = protocol.decode_message(self._message_type, blob)
return msg | [
"def",
"_from_base_type",
"(",
"self",
",",
"ent",
")",
":",
"if",
"ent",
".",
"_projection",
":",
"# Projection query result. Reconstitute the message from the fields.",
"return",
"_projected_entity_to_message",
"(",
"ent",
",",
"self",
".",
"_message_type",
")",
"blob",
"=",
"ent",
".",
"blob_",
"if",
"blob",
"is",
"not",
"None",
":",
"protocol",
"=",
"self",
".",
"_protocol_impl",
"else",
":",
"# Perhaps it was written using a different protocol.",
"protocol",
"=",
"None",
"for",
"name",
"in",
"_protocols_registry",
".",
"names",
":",
"key",
"=",
"'__%s__'",
"%",
"name",
"if",
"key",
"in",
"ent",
".",
"_values",
":",
"blob",
"=",
"ent",
".",
"_values",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"blob",
",",
"model",
".",
"_BaseValue",
")",
":",
"blob",
"=",
"blob",
".",
"b_val",
"protocol",
"=",
"_protocols_registry",
".",
"lookup_by_name",
"(",
"name",
")",
"break",
"if",
"blob",
"is",
"None",
"or",
"protocol",
"is",
"None",
":",
"return",
"None",
"# This will reveal the underlying dummy model.",
"msg",
"=",
"protocol",
".",
"decode_message",
"(",
"self",
".",
"_message_type",
",",
"blob",
")",
"return",
"msg"
] | Convert a Model instance (entity) to a Message value. | [
"Convert",
"a",
"Model",
"instance",
"(",
"entity",
")",
"to",
"a",
"Message",
"value",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/msgprop.py#L370-L393 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/polymodel.py | _ClassKeyProperty._get_value | 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 | python | 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 | [
"def",
"_get_value",
"(",
"self",
",",
"entity",
")",
":",
"value",
"=",
"super",
"(",
"_ClassKeyProperty",
",",
"self",
")",
".",
"_get_value",
"(",
"entity",
")",
"if",
"not",
"value",
":",
"value",
"=",
"entity",
".",
"_class_key",
"(",
")",
"self",
".",
"_store_value",
"(",
"entity",
",",
"value",
")",
"return",
"value"
] | Compute and store a default value if necessary. | [
"Compute",
"and",
"store",
"a",
"default",
"value",
"if",
"necessary",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/polymodel.py#L74-L80 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/polymodel.py | PolyModel._update_kind_map | def _update_kind_map(cls):
"""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 class
names, like regular Model class names, must be globally unique.
"""
cls._kind_map[cls._class_name()] = cls
class_key = cls._class_key()
if class_key:
cls._class_map[tuple(class_key)] = cls | python | def _update_kind_map(cls):
"""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 class
names, like regular Model class names, must be globally unique.
"""
cls._kind_map[cls._class_name()] = cls
class_key = cls._class_key()
if class_key:
cls._class_map[tuple(class_key)] = cls | [
"def",
"_update_kind_map",
"(",
"cls",
")",
":",
"cls",
".",
"_kind_map",
"[",
"cls",
".",
"_class_name",
"(",
")",
"]",
"=",
"cls",
"class_key",
"=",
"cls",
".",
"_class_key",
"(",
")",
"if",
"class_key",
":",
"cls",
".",
"_class_map",
"[",
"tuple",
"(",
"class_key",
")",
"]",
"=",
"cls"
] | 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 class
names, like regular Model class names, must be globally unique. | [
"Override",
";",
"called",
"by",
"Model",
".",
"_fix_up_properties",
"()",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/polymodel.py#L168-L180 | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/polymodel.py | PolyModel._from_pb | 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_property_list()]:
for p in plist:
if p.name() == prop_name:
class_name.append(p.value().stringvalue())
cls = cls._class_map.get(tuple(class_name), cls)
return super(PolyModel, cls)._from_pb(pb, set_key, ent, key) | python | 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_property_list()]:
for p in plist:
if p.name() == prop_name:
class_name.append(p.value().stringvalue())
cls = cls._class_map.get(tuple(class_name), cls)
return super(PolyModel, cls)._from_pb(pb, set_key, ent, key) | [
"def",
"_from_pb",
"(",
"cls",
",",
"pb",
",",
"set_key",
"=",
"True",
",",
"ent",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"prop_name",
"=",
"cls",
".",
"class_",
".",
"_name",
"class_name",
"=",
"[",
"]",
"for",
"plist",
"in",
"[",
"pb",
".",
"property_list",
"(",
")",
",",
"pb",
".",
"raw_property_list",
"(",
")",
"]",
":",
"for",
"p",
"in",
"plist",
":",
"if",
"p",
".",
"name",
"(",
")",
"==",
"prop_name",
":",
"class_name",
".",
"append",
"(",
"p",
".",
"value",
"(",
")",
".",
"stringvalue",
"(",
")",
")",
"cls",
"=",
"cls",
".",
"_class_map",
".",
"get",
"(",
"tuple",
"(",
"class_name",
")",
",",
"cls",
")",
"return",
"super",
"(",
"PolyModel",
",",
"cls",
")",
".",
"_from_pb",
"(",
"pb",
",",
"set_key",
",",
"ent",
",",
"key",
")"
] | Override.
Use the class map to give the entity the correct subclass. | [
"Override",
"."
] | cf4cab3f1f69cd04e1a9229871be466b53729f3f | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/polymodel.py#L183-L195 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.