|
| 1 | +# |
| 2 | +# Copyright 2015 The ndb Authors. All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import atexit |
| 17 | +import code |
| 18 | +import readline |
| 19 | +import os |
| 20 | +import sys |
| 21 | + |
| 22 | +import ndb |
| 23 | +from ndb import tasklets |
| 24 | +from ndb.google_imports import datastore_pbs |
| 25 | + |
| 26 | +HISTORY_PATH = os.path.expanduser('~/.ndb_shell_history') |
| 27 | + |
| 28 | +def shell(): |
| 29 | + |
| 30 | + if (not os.environ.get('DATASTORE_APP_ID', None) |
| 31 | + and not os.environ.get('DATASTORE_PROJECT_ID', None)): |
| 32 | + raise ValueError('Must set either DATASTORE_APP_ID or DATASTORE_PROJECT_ID' |
| 33 | + ' environment variable.') |
| 34 | + |
| 35 | + ndb.get_context().set_memcache_policy(False) |
| 36 | + ndb.get_context().set_cache_policy(False) |
| 37 | + |
| 38 | + # ndb will set the application ID. |
| 39 | + application_id = os.environ['APPLICATION_ID'] |
| 40 | + id_resolver = datastore_pbs.IdResolver((application_id,)) |
| 41 | + project_id = id_resolver.resolve_project_id(application_id) |
| 42 | + |
| 43 | + banner = """ndb shell |
| 44 | + Python %s |
| 45 | + Project: %s |
| 46 | + The ndb module is already imported. |
| 47 | + """ % (sys.version, project_id) |
| 48 | + |
| 49 | + imports = { |
| 50 | + 'ndb': ndb, |
| 51 | + } |
| 52 | + |
| 53 | + # set up the environment |
| 54 | + os.environ['SERVER_SOFTWARE'] = 'Development (ndb_shell)/0.1' |
| 55 | + |
| 56 | + sys.ps1 = '%s> ' % project_id |
| 57 | + if readline is not None: |
| 58 | + # set up readline |
| 59 | + readline.parse_and_bind('tab: complete') |
| 60 | + atexit.register(lambda: readline.write_history_file(HISTORY_PATH)) |
| 61 | + if os.path.exists(HISTORY_PATH): |
| 62 | + readline.read_history_file(HISTORY_PATH) |
| 63 | + |
| 64 | + code.interact(banner=banner, local=imports) |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + shell() |
0 commit comments