Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a263242

Browse files
committed
Add task_list demo.
1 parent 9b39b1b commit a263242

File tree

9 files changed

+243
-9
lines changed

9 files changed

+243
-9
lines changed

demo/README.md

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1-
# ndb demo application
1+
# ndb demo applications
22

33
## Overview
44

5+
There are three separate demos:
6+
7+
* app: a Google App Engine application with a set of example uses
8+
* shell: an application that sets up the ndb environment then opens up a python shell for you to interact with.
9+
* task_list: a basic application which runs inside Compute Engine.
10+
11+
## app (App Engine Application)
12+
513
This demo shows various ways to use ndb. The application consists of serveral
614
different handlers.
715
* hello.py: a simple hello world application.
@@ -13,7 +21,7 @@ different handlers.
1321

1422
This folder also has a demo for using ndb from outside of App Engine. You can use `shell.py` to interact with your Datastore using ndb through the Cloud Datastore API.
1523

16-
## Setup (demo application)
24+
### Setup
1725

1826
1. Copy ndb (the entire folder) into the demo subdirectory.
1927
2. Deploy the demo application using the command:
@@ -24,18 +32,44 @@ This folder also has a demo for using ndb from outside of App Engine. You can us
2432

2533
gcloud config set project <project-id>
2634

27-
## Shell
35+
## shell
36+
37+
1. Follow the instructions below to setup ndb in GCE.
38+
39+
2. Run the shell. From here you can write ndb code to interact with Datastore. Don't forget, this shell is interacting with the production Datastore of your <project-id>.
40+
41+
python demo/shell.py
42+
43+
## Task List
44+
45+
1. Follow the instructions below to setup ndb in GCE.
46+
47+
2. Run the task list application. Don't forget, this application is interacting with the production Datastore of your <project-id>.
48+
49+
python demo/task_list.py
2850

29-
1. First, ensure your environment is setup.
51+
# Setup from your local machine or from Google Compute Engine
52+
53+
1. Install pip
54+
55+
sudo apt-get update
56+
sudo apt-get install python-pip
57+
58+
2. Install the Google App Engine SDK and point ndb to the installation. If you installed `gcloud` to a different location then your App Engine SDK may be installed in a different location.
59+
60+
sudo gcloud components install app-engine-python
61+
export GAE=/usr/local/share/google/google-cloud-sdk/platform/google_appengine
62+
63+
3. Install ndb
64+
65+
pip install --pre ndb
66+
67+
4. Setup your environment.
3068

3169
export DATASTORE_PROJECT_ID=<project-id>
3270
export DATASTORE_USE_PROJECT_ID_AS_APP_ID=true
3371

34-
2. Then, make sure you have authenticated using gcloud.
72+
5. Finally, make sure you have authenticated using gcloud.
3573

3674
gcloud auth login
3775

38-
3. Finally, run the shell. From here you can write ndb code to interact with Datastore. Don't forget, this shell is interacting with the production Datastore of your <project-id>.
39-
40-
python demo/shell.py
41-

demo/app/__init__.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#
2+
# Copyright 2016 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+
17+
# This file intentionally left blank.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

demo/task_list.py

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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

Comments
 (0)