本文整理汇总了Python中google.appengine.ext.ndb.KeyProperty方法的典型用法代码示例。如果您正苦于以下问题:Python ndb.KeyProperty方法的具体用法?Python ndb.KeyProperty怎么用?Python ndb.KeyProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.appengine.ext.ndb
的用法示例。
在下文中一共展示了ndb.KeyProperty方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query_purchase_with_customer_key
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def query_purchase_with_customer_key():
# [START purchase_with_customer_key_models]
class Customer(ndb.Model):
name = ndb.StringProperty()
class Purchase(ndb.Model):
customer = ndb.KeyProperty(kind=Customer)
price = ndb.IntegerProperty()
# [END purchase_with_customer_key_models]
def query_purchases_for_customer_via_key(customer_entity):
purchases = Purchase.query(
Purchase.customer == customer_entity.key).fetch()
return purchases
return Customer, Purchase, query_purchases_for_customer_via_key
示例2: convert_KeyProperty
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def convert_KeyProperty(self, model, prop, kwargs):
"""Returns a form field for a ``ndb.KeyProperty``."""
if 'reference_class' not in kwargs:
try:
reference_class = prop._kind
except AttributeError:
reference_class = prop._reference_class
if isinstance(reference_class, string_types):
# reference class is a string, try to retrieve the model object.
mod = __import__(model.__module__, None, None, [reference_class], 0)
reference_class = getattr(mod, reference_class)
kwargs['reference_class'] = reference_class
kwargs.setdefault('allow_blank', not prop._required)
return KeyPropertyField(**kwargs)
示例3: convert_ndb_key_propety
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def convert_ndb_key_propety(ndb_key_prop, registry=None):
"""
Two conventions for handling KeyProperties:
#1.
Given:
store_key = ndb.KeyProperty(...)
Result is 2 fields:
store_id = graphene.String() -> resolves to store_key.urlsafe()
store = NdbKeyField() -> resolves to entity
#2.
Given:
store = ndb.KeyProperty(...)
Result is 2 fields:
store_id = graphene.String() -> resolves to store_key.urlsafe()
store = NdbKeyField() -> resolves to entity
"""
is_repeated = ndb_key_prop._repeated
name = ndb_key_prop._code_name
if name.endswith('_key') or name.endswith('_keys'):
# Case #1 - name is of form 'store_key' or 'store_keys'
string_prop_name = rreplace(name, '_key', '_id', 1)
resolved_prop_name = name[:-4] if name.endswith('_key') else p.plural(name[:-5])
else:
# Case #2 - name is of form 'store'
singular_name = p.singular_noun(name) if p.singular_noun(name) else name
string_prop_name = singular_name + '_ids' if is_repeated else singular_name + '_id'
resolved_prop_name = name
return [
ConversionResult(name=string_prop_name, field=DynamicNdbKeyStringField(ndb_key_prop, registry=registry)),
ConversionResult(name=resolved_prop_name, field=DynamicNdbKeyReferenceField(ndb_key_prop, registry=registry))
]
示例4: testKeyProperty_withSuffix
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def testKeyProperty_withSuffix(self):
my_registry = Registry()
class User(ndb.Model):
name = ndb.StringProperty()
class UserType(NdbObjectType):
class Meta:
model = User
registry = my_registry
prop = ndb.KeyProperty(kind='User')
prop._code_name = 'user_key'
conversion = convert_ndb_property(prop, my_registry)
self.assertLength(conversion, 2)
self.assertEqual(conversion[0].name, 'user_id')
self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
_type = conversion[0].field.get_type()
self.assertIsInstance(_type, NdbKeyStringField)
self.assertEqual(_type._type, String)
self.assertEqual(conversion[1].name, 'user')
self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
_type = conversion[1].field.get_type()
self.assertIsInstance(_type, NdbKeyReferenceField)
self.assertEqual(_type._type, UserType)
示例5: testKeyProperty_withSuffix_repeated
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def testKeyProperty_withSuffix_repeated(self):
my_registry = Registry()
class User(ndb.Model):
name = ndb.StringProperty()
class UserType(NdbObjectType):
class Meta:
model = User
registry = my_registry
prop = ndb.KeyProperty(kind='User', repeated=True)
prop._code_name = 'user_keys'
conversion = convert_ndb_property(prop, my_registry)
self.assertLength(conversion, 2)
self.assertEqual(conversion[0].name, 'user_ids')
self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
_type = conversion[0].field.get_type()
self.assertIsInstance(_type, NdbKeyStringField)
self.assertIsInstance(_type._type, List)
self.assertEqual(_type._type.of_type, String)
self.assertEqual(conversion[1].name, 'users')
self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
_type = conversion[1].field.get_type()
self.assertIsInstance(_type, NdbKeyReferenceField)
self.assertIsInstance(_type._type, List)
self.assertEqual(_type._type.of_type, UserType)
示例6: testKeyProperty_withSuffix_required
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def testKeyProperty_withSuffix_required(self):
class User(ndb.Model):
name = ndb.StringProperty()
my_registry = Registry()
class UserType(NdbObjectType):
class Meta:
model = User
registry = my_registry
prop = ndb.KeyProperty(kind='User', required=True)
prop._code_name = 'user_key'
conversion = convert_ndb_property(prop, my_registry)
self.assertLength(conversion, 2)
self.assertEqual(conversion[0].name, 'user_id')
self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
_type = conversion[0].field.get_type()
self.assertIsInstance(_type, NdbKeyStringField)
self.assertIsInstance(_type._type, NonNull)
self.assertEqual(_type._type.of_type, String)
self.assertEqual(conversion[1].name, 'user')
self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
_type = conversion[1].field.get_type()
self.assertIsInstance(_type, NdbKeyReferenceField)
self.assertIsInstance(_type._type, NonNull)
self.assertEqual(_type._type.of_type, UserType)
示例7: testKeyProperty_withoutSuffix
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def testKeyProperty_withoutSuffix(self):
my_registry = Registry()
class User(ndb.Model):
name = ndb.StringProperty()
class UserType(NdbObjectType):
class Meta:
model = User
registry = my_registry
prop = ndb.KeyProperty(kind='User')
prop._code_name = 'user'
conversion = convert_ndb_property(prop, my_registry)
self.assertLength(conversion, 2)
self.assertEqual(conversion[0].name, 'user_id')
self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
_type = conversion[0].field.get_type()
self.assertIsInstance(_type, NdbKeyStringField)
self.assertEqual(_type._type, String)
self.assertEqual(conversion[1].name, 'user')
self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
_type = conversion[1].field.get_type()
self.assertIsInstance(_type, NdbKeyReferenceField)
self.assertEqual(_type._type, UserType)
示例8: _get_keys_and_properties
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def _get_keys_and_properties(cls):
keys = {}
for name, property_type in cls._properties.items():
if isinstance(property_type, ndb.KeyProperty):
keys[name] = property_type._kind, property_type._repeated
return keys
示例9: __from_type_to_raw_value
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def __from_type_to_raw_value(cls, field, value):
types = {'StringProperty': cls.__decode_str,
'IntegerProperty': cls.__to_int,
'FloatProperty': cls.__to_float,
'DateTimeProperty': cls._convert_date,
'BooleanProperty': bool,
'BlobKeyProperty': cls.__blob_to_url,
'TextProperty': cls.__decode_str,
'KeyProperty': cls.__key_property_to_id}
field_type = type(field).__name__
return types[field_type](value) if field_type in types else None
示例10: _validate_filters_ndb
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def _validate_filters_ndb(cls, filters, model_class):
"""Validate ndb.Model filters."""
if not filters:
return
properties = model_class._properties
for idx, f in enumerate(filters):
prop, ineq, val = f
if prop not in properties:
raise errors.BadReaderParamsError(
"Property %s is not defined for entity type %s",
prop, model_class._get_kind())
# Attempt to cast the value to a KeyProperty if appropriate.
# This enables filtering against keys.
try:
if (isinstance(val, basestring) and
isinstance(properties[prop],
(ndb.KeyProperty, ndb.ComputedProperty))):
val = ndb.Key(urlsafe=val)
filters[idx] = [prop, ineq, val]
except:
pass
# Validate the value of each filter. We need to know filters have
# valid value to carry out splits.
try:
properties[prop]._do_validate(val)
except db.BadValueError, e:
raise errors.BadReaderParamsError(e)
示例11: _CoerceQueryParam
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def _CoerceQueryParam(field, query_param):
"""Attempts to coerce `query_param` to match the ndb type of `field`.
Args:
field: The ndb field being queried.
query_param: The query term to be coerced.
Returns:
The query param coerced if a coercion was possible.
Raises:
QueryTypeError: If there is an error with the type conversion.
"""
if isinstance(field, ndb.IntegerProperty):
try:
return int(query_param)
except ValueError:
raise QueryTypeError(
'Query param "%s" could not be converted to integer' % query_param)
elif isinstance(field, ndb.BooleanProperty):
if query_param.lower() == 'true':
return True
elif query_param.lower() == 'false':
return False
else:
raise QueryTypeError(
'Query param "%s" could not be converted to boolean' % query_param)
elif isinstance(field, ndb.KeyProperty):
key = datastore_utils.GetKeyFromUrlsafe(query_param)
if not key:
raise QueryTypeError(
'Query param "%s" could not be converted to ndb.Key' % query_param)
return key
else:
return query_param
示例12: _value_to_property
# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import KeyProperty [as 别名]
def _value_to_property(self, value, prop):
"""Converts raw data value into an appropriate NDB property"""
if isinstance(prop, ndb.KeyProperty):
if value is None:
return None
try:
return ndb.Key(urlsafe=value)
except ProtocolBufferDecodeError as e:
if prop._kind is not None:
model_class = ndb.Model._kind_map.get(prop._kind)
if getattr(model_class, 'RESTMeta', None) and getattr(model_class.RESTMeta, 'use_input_id', False):
return ndb.Key(model_class, value)
raise RESTException('invalid key: {}'.format(value) )
elif isinstance(prop, ndb.TimeProperty):
if dateutil is None:
try:
return datetime.strptime(value, "%H:%M:%S").time()
except ValueError as e:
raise RESTException("Invalid time. Must be in ISO 8601 format.")
else:
return dateutil.parser.parse(value).time()
elif isinstance(prop, ndb.DateProperty):
if dateutil is None:
try:
return datetime.strptime(value, "%Y-%m-%d").date()
except ValueError as e:
raise RESTException("Invalid date. Must be in ISO 8601 format.")
else:
return dateutil.parser.parse(value).date()
elif isinstance(prop, ndb.DateTimeProperty):
if dateutil is None:
try:
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
except ValueError as e:
raise RESTException("Invalid datetime. Must be in ISO 8601 format.")
else:
return dateutil.parser.parse(value)
elif isinstance(prop, ndb.GeoPtProperty):
# Convert from string (formatted as '52.37, 4.88') to GeoPt
return ndb.GeoPt(value)
elif isinstance(prop, ndb.StructuredProperty):
# It's a structured property - the input data is a dict - recursively parse it as well
return self._build_model_from_data(value, prop._modelclass)
else:
# Return as-is (no need for further manipulation)
return value