我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用google.appengine.ext.ndb.Query()。
def make_directed_query(self, kind_class, keys_only=False): """Construct a query for this key range, including the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, use keys_only on Query? Returns: A db.Query or ndb.Query instance (corresponding to kind_class). Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_directed_ndb_query(kind_class, keys_only=keys_only) assert self._app is None, '_app is not supported for db.Query' direction = self.__get_direction("", "-") query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("%s__key__" % direction) query = self.filter_query(query) return query
def make_directed_datastore_query(self, kind, keys_only=False): """Construct a query for this key range, including the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? Returns: A datastore.Query instance. Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC). """ direction = self.__get_direction(datastore.Query.ASCENDING, datastore.Query.DESCENDING) query = datastore.Query(kind, _app=self._app, keys_only=keys_only) query.Order(("__key__", direction)) query = self.filter_datastore_query(query) return query
def make_ascending_query(self, kind_class, keys_only=False, filters=None): """Construct a query for this key range without setting the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, query only for keys. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: A db.Query or ndb.Query instance (corresponding to kind_class). """ if ndb is not None: if issubclass(kind_class, ndb.Model): return self.make_ascending_ndb_query( kind_class, keys_only=keys_only, filters=filters) assert self._app is None, '_app is not supported for db.Query' query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only) query.order("__key__") query = self.filter_query(query, filters=filters) return query
def make_ascending_ndb_query(self, kind_class, keys_only=False, filters=None): """Construct an NDB query for this key range, without the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, query only for keys. Returns: An ndb.Query instance. """ assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query, filters=filters) query = query.order(kind_class._key) return query
def make_ascending_datastore_query(self, kind, keys_only=False, filters=None): """Construct a query for this key range without setting the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: A datastore.Query instance. """ query = datastore.Query(kind, namespace=self.namespace, _app=self._app, keys_only=keys_only) query.Order(("__key__", datastore.Query.ASCENDING)) query = self.filter_datastore_query(query, filters=filters) return query
def testDeleteTournament(self): self.loginUser() id = self.AddBasicTournament() id2 = self.AddBasicTournament() self.assertEqual(16, len(ndb.Query(kind = "PlayerPair").fetch())) response = self.testapp.delete("/api/tournaments/{}".format(id)) self.assertEqual(response.status_int, 204) response = self.testapp.get("/api/tournaments/{}".format(id), expect_errors=True) self.assertEqual(response.status_int, 404) self.assertEqual(8, len(ndb.Query(kind = "PlayerPair").fetch())) response = self.testapp.get("/api/tournaments") tourneys = json.loads(response.body) self.assertIsNotNone(tourneys["tournaments"]) self.assertEqual(1, len(tourneys["tournaments"])) self.assertEqual(id2, tourneys["tournaments"][0]["id"]) response = self.testapp.get("/api/tournaments/{}".format(id2), expect_errors=True) self.CheckBasicTournamentMetadataUnchanged(json.loads(response.body))
def GetBackupXML(): thisdate = datetime.datetime.now() xml = '<?xml version="1.0" encoding="utf-8"?>\r\n<data date="' + thisdate.isoformat() + '">\r\n' kinds = metadata.get_kinds() for kind in kinds: if kind.startswith('_'): pass # Ignore kinds that begin with _, they are internal to GAE else: q = ndb.Query(kind=kind) all = q.fetch() for e in all: xml += '<' + kind + '>\r\n' for n, v in e._properties.items(): xml += ' <' + n + '>' xml += str(getattr(e, n)) xml += '</' + n + '>\r\n' xml += '</' + kind + '>\r\n' xml += '</data>' return xml
def test_query(self): """ Encoding a L{ndb.Query} should be returned as a list. """ query = models.SimpleEntity.query() self.assertIsInstance(query, ndb.Query) self.assertEncodes(query, ( '\n\x00\x00\x00\x00' ), encoding=pyamf.AMF0) self.assertEncodes(query, ( '\t\x01\x01' ), encoding=pyamf.AMF3)
def _IsNdbQuery(query): return ndb is not None and isinstance(query, ndb.Query)
def filter_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: A db.Query or ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ if ndb is not None: if _IsNdbQuery(query): return self.filter_ndb_query(query, filters=filters) assert not _IsNdbQuery(query) if filters: for f in filters: query.filter("%s %s" % (f[0], f[1]), f[2]) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query.filter("__key__ %s" % start_comparator, self.key_start) if self.key_end: query.filter("__key__ %s" % end_comparator, self.key_end) return query
def filter_ndb_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: An ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ assert _IsNdbQuery(query) if filters: for f in filters: query = query.filter(ndb.FilterNode(*f)) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query = query.filter(ndb.FilterNode("__key__", start_comparator, self.key_start)) if self.key_end: query = query.filter(ndb.FilterNode("__key__", end_comparator, self.key_end)) return query
def filter_datastore_query(self, query, filters=None): """Add query filter to restrict to this key range. Args: query: A datastore.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range. """ assert isinstance(query, datastore.Query) if filters: for f in filters: query.update({"%s %s" % (f[0], f[1]): f[2]}) if self.include_start: start_comparator = ">=" else: start_comparator = ">" if self.include_end: end_comparator = "<=" else: end_comparator = "<" if self.key_start: query.update({"__key__ %s" % start_comparator: self.key_start}) if self.key_end: query.update({"__key__ %s" % end_comparator: self.key_end}) return query
def testDeleteTournament_hands_removed(self): self.loginUser() id = self.AddBasicTournament() id2 = self.AddBasicTournament() params = {'calls': {}, 'ns_score': 25, 'ew_score': 75} self.testapp.put_json("/api/tournaments/{}/hands/1/2/3".format(id), params) params = {'calls': {"south" : "T"}, 'ns_score': 225, 'ew_score': -25} self.testapp.put_json("/api/tournaments/{}/hands/1/2/3".format(id2), params) self.assertEqual(2, len(ndb.Query(kind = "HandScore").fetch())) response = self.testapp.delete("/api/tournaments/{}".format(id)) self.assertEqual(response.status_int, 204) response = self.testapp.get("/api/tournaments/{}".format(id), expect_errors=True) self.assertEqual(response.status_int, 404) self.assertEqual(1, len(ndb.Query(kind = "HandScore").fetch())) response = self.testapp.get("/api/tournaments") tourneys = json.loads(response.body) self.assertIsNotNone(tourneys["tournaments"]) self.assertEqual(1, len(tourneys["tournaments"])) self.assertEqual(id2, tourneys["tournaments"][0]["id"]) response = self.testapp.get("/api/tournaments/{}".format(id2), expect_errors=True) response_dict = json.loads(response.body) self.CheckBasicTournamentMetadataUnchanged(response_dict) self.assertEqual({"south" : "T"}, response_dict["hands"][0]['calls']) self.assertEqual(225, response_dict["hands"][0]['ns_score']) self.assertEqual(-25, response_dict["hands"][0]['ew_score']) self.assertEqual(1, response_dict["hands"][0]['board_no']) self.assertEqual(2, response_dict["hands"][0]['ns_pair']) self.assertEqual(3, response_dict["hands"][0]['ew_pair'])
def main(project_id): remote_api_stub.ConfigureRemoteApiForOAuth( '{}.appspot.com'.format(project_id), '/_ah/remote_api') # List the first 10 keys in the datastore. keys = ndb.Query().fetch(10, keys_only=True) for key in keys: print(key)