|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# Copyright 2015 Google Inc. All Rights Reserved. |
| 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 | +# [START all] |
| 16 | +"""Sample for Cloud Datastore using the NDB client library. |
| 17 | +
|
| 18 | +This is a command-line task list manager. |
| 19 | +
|
| 20 | +From the command line, first setup the necessary environment variables. |
| 21 | +export DATASTORE_PROJECT_ID=<my-project-id> |
| 22 | +export DATASTORE_USE_PROJECT_ID_AS_APP_ID=true |
| 23 | +""" |
| 24 | + |
| 25 | +import ndb |
| 26 | +# [START build_service] |
| 27 | +# When running outside of App Engine, ndb caching policies should be adjusted. |
| 28 | +# The local cache is never evicted, so it should be turned off for any long |
| 29 | +# running processes. In order to use memcache, App Engine Remote API must be |
| 30 | +# installed. Note that if you are running ndb both inside and outside of |
| 31 | +# App Engine, your memcache policies *must* match. Otherwise, calling put may |
| 32 | +# not invalidate your cache and App Engine ndb will get stale results. |
| 33 | +ndb.get_context().set_cache_policy(False) |
| 34 | +ndb.get_context().set_memcache_policy(False) |
| 35 | +# [END build_service] |
| 36 | + |
| 37 | + |
| 38 | +# [START add_entity] |
| 39 | +# Define the model we will be using for the tasks. |
| 40 | +class Task(ndb.Model): |
| 41 | + description = ndb.StringProperty() |
| 42 | + created = ndb.DateTimeProperty(auto_now_add=True) |
| 43 | + done = ndb.BooleanProperty(default=False) |
| 44 | + |
| 45 | + |
| 46 | +def add_task(description): |
| 47 | + """Adds a new task to the Datastore. |
| 48 | +
|
| 49 | + Args: |
| 50 | + description: A string description of the task. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + The key of the entity that was put. |
| 54 | + """ |
| 55 | + return Task(description=description).put() |
| 56 | +# [END add_entity] |
| 57 | + |
| 58 | + |
| 59 | +# [START update_entity] |
| 60 | +@ndb.transactional |
| 61 | +def mark_done(task_id): |
| 62 | + """Marks a task as done. |
| 63 | +
|
| 64 | + Args: |
| 65 | + task_id: The integer id of the task to update. |
| 66 | +
|
| 67 | + Raises: |
| 68 | + ValueError: if the requested task doesn't exist. |
| 69 | + """ |
| 70 | + task = Task.get_by_id(task_id) |
| 71 | + if task is None: |
| 72 | + raise ValueError('Task with id %d does not exist' % task_id) |
| 73 | + task.done = True |
| 74 | + task.put() |
| 75 | +# [END update_entity] |
| 76 | + |
| 77 | + |
| 78 | +# [START retrieve_entities] |
| 79 | +def list_tasks(): |
| 80 | + """Lists all the task entities in ascending order of completion time. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + A list of tasks. |
| 84 | + """ |
| 85 | + # Querying the tasks without an ancestor is eventually consistent. |
| 86 | + return list(Task.query().order(Task.created)) |
| 87 | +# [END retrieve_entities] |
| 88 | + |
| 89 | + |
| 90 | +# [START delete_entity] |
| 91 | +def delete_task(task_id): |
| 92 | + """Deletes the given task. |
| 93 | +
|
| 94 | + Args: |
| 95 | + task_id: The integer id of the task to delete. |
| 96 | + """ |
| 97 | + ndb.Key('Task', task_id).delete() |
| 98 | +# [END delete_entity] |
| 99 | + |
| 100 | + |
| 101 | +# [START format_results] |
| 102 | +def format_tasks(tasks): |
| 103 | + """Converts a list of tasks to a list of string representations. |
| 104 | +
|
| 105 | + Args: |
| 106 | + tasks: A list of the tasks to convert. |
| 107 | + Returns: |
| 108 | + A list of string formatted tasks. |
| 109 | + """ |
| 110 | + return ['%d : %s (%s)' % (task.key.id(), |
| 111 | + task.description, |
| 112 | + ('done' if task.done |
| 113 | + else 'created %s' % task.created)) |
| 114 | + for task in tasks] |
| 115 | +# [END format_results] |
| 116 | + |
| 117 | + |
| 118 | +def get_arg(cmds): |
| 119 | + """Accepts a split string command and validates its size. |
| 120 | +
|
| 121 | + Args: |
| 122 | + cmds: A split command line as a list of strings. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + The string argument to the command. |
| 126 | +
|
| 127 | + Raises: |
| 128 | + ValueError: If there is no argument. |
| 129 | + """ |
| 130 | + if len(cmds) != 2: |
| 131 | + raise ValueError('%s needs an argument.' % cmds[0]) |
| 132 | + return cmds[1] |
| 133 | + |
| 134 | + |
| 135 | +def handle_command(command): |
| 136 | + """Accepts a string command and performs an action. |
| 137 | +
|
| 138 | + Args: |
| 139 | + command: the command to run as a string. |
| 140 | + """ |
| 141 | + try: |
| 142 | + cmds = command.split(None, 1) |
| 143 | + cmd = cmds[0] |
| 144 | + if cmd == 'new': |
| 145 | + add_task(get_arg(cmds)) |
| 146 | + elif cmd == 'done': |
| 147 | + mark_done(int(get_arg(cmds))) |
| 148 | + elif cmd == 'list': |
| 149 | + for task in format_tasks(list_tasks()): |
| 150 | + print task |
| 151 | + elif cmd == 'delete': |
| 152 | + delete_task(int(get_arg(cmds))) |
| 153 | + else: |
| 154 | + print_usage() |
| 155 | + except Exception, e: # pylint: disable=broad-except |
| 156 | + print e |
| 157 | + print_usage() |
| 158 | + |
| 159 | + |
| 160 | +def print_usage(): |
| 161 | + """Print the usage of our task list command.""" |
| 162 | + print 'Usage:' |
| 163 | + print '' |
| 164 | + print ' new <description> Adds a task with a description <description>' |
| 165 | + print ' done <task-id> Marks a task as done' |
| 166 | + print ' list Lists all tasks by creation time' |
| 167 | + print ' delete <task-id> Deletes a task' |
| 168 | + print '' |
| 169 | + |
| 170 | + |
| 171 | +def main(): |
| 172 | + print 'Cloud Datastore Task List' |
| 173 | + print '' |
| 174 | + print_usage() |
| 175 | + while True: |
| 176 | + line = raw_input('> ') |
| 177 | + if not line: |
| 178 | + break |
| 179 | + handle_command(line) |
| 180 | + |
| 181 | +if __name__ == '__main__': |
| 182 | + main() |
| 183 | +# [END all] |
0 commit comments