Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 """Fetches entities and iterate over and process them.""" | |
| 6 | |
| 7 import os | |
| 8 | |
| 9 import remote_api | |
| 10 | |
| 11 _DEFAULT_BATCH_SIZE = 1000 | |
| 12 | |
| 13 | |
| 14 def ProjectEntity(entity, fields): | |
| 15 """Projects fields from entity. Returns dict.""" | |
| 16 entity_info = {} | |
| 17 for field in fields: | |
| 18 if hasattr(entity, field): | |
| 19 entity_info[field] = getattr(entity, field) | |
| 20 else: | |
| 21 entity_info[field] = None | |
| 22 entity_info['id'] = entity.key.id() | |
| 23 return entity_info | |
| 24 | |
| 25 | |
| 26 def Iterate(query, | |
| 27 fields, | |
| 28 filter_func=None, | |
| 29 batch_size=_DEFAULT_BATCH_SIZE, | |
| 30 batch_run=False, | |
| 31 app_id=None): | |
| 32 """Iterates entities queried by query. | |
| 33 | |
| 34 Args: | |
| 35 query (ndb.Query): The query to fetch entities. | |
| 36 fields (list): Field names of an entity to be projected to a dict. | |
| 37 If a given field name is not available, it is set to None. | |
| 38 'id' is always added by default as an integer. | |
| 39 filter_func (function): A function that does in memory filtering. | |
| 40 batch_size (int): The number of entities to query at one time. | |
| 41 batch_run (bool): If True, iterate batches of entities, if | |
| 42 False, iterate each entity. | |
| 43 app_id (str): App engine app id. | |
| 44 | |
| 45 An exmaple is available in crash_printer/print_crash.py. | |
| 46 """ | |
| 47 if app_id: | |
| 48 remote_api.EnableRemoteApi(app_id) | |
| 49 else: | |
| 50 remote_api.EnableRemoteApi() | |
|
stgao
2016/10/13 06:38:52
Why we don'd expect an app id? What's the default
Sharu Jiang
2016/10/13 20:31:16
I think this iterator can be used not only for cra
stgao
2016/10/14 00:55:01
It could be reused, but this style of default valu
stgao
2016/10/19 00:49:47
Ping.
Sharu Jiang
2016/10/19 20:12:44
Done.
| |
| 51 | |
| 52 cursor = None | |
| 53 while True: | |
| 54 entities, next_cursor, more = query.fetch_page(batch_size, | |
| 55 start_cursor=cursor) | |
| 56 | |
| 57 if not more: | |
| 58 break | |
| 59 | |
| 60 if filter_func: | |
| 61 entities = filter_func(entities) | |
| 62 | |
| 63 entities = [ProjectEntity(entity, fields) for entity in entities] | |
| 64 | |
| 65 if batch_run: | |
| 66 yield entities | |
| 67 else: | |
| 68 for entity in entities: | |
| 69 yield entity | |
| 70 | |
| 71 cursor = next_cursor | |
| OLD | NEW |