Python google.appengine.ext.ndb.KeyProperty() Examples
The following are 14
code examples of google.appengine.ext.ndb.KeyProperty().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
google.appengine.ext.ndb
, or try the search function
.
Example #1
Source File: snippets.py From python-docs-samples with Apache License 2.0 | 6 votes |
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
Example #2
Source File: ndb.py From jbox with MIT License | 5 votes |
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)
Example #3
Source File: ndb.py From RSSNewsGAE with Apache License 2.0 | 5 votes |
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)
Example #4
Source File: converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)) ]
Example #5
Source File: test_converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #6
Source File: test_converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #7
Source File: test_converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #8
Source File: test_converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #9
Source File: all.py From ray with MIT License | 5 votes |
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
Example #10
Source File: all.py From ray with MIT License | 5 votes |
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
Example #11
Source File: ndb.py From googleapps-message-recall with Apache License 2.0 | 5 votes |
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)
Example #12
Source File: input_readers.py From appengine-mapreduce with Apache License 2.0 | 5 votes |
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)
Example #13
Source File: handler_utils.py From upvote with Apache License 2.0 | 5 votes |
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
Example #14
Source File: rest_gae.py From rest_gae with Apache License 2.0 | 4 votes |
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