Skip to content
This repository has been archived by the owner on Dec 25, 2023. It is now read-only.

Commit

Permalink
Add task_list demo.
Browse files Browse the repository at this point in the history
  • Loading branch information
pcostell committed Mar 25, 2016
1 parent 9b39b1b commit a263242
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 9 deletions.
52 changes: 43 additions & 9 deletions demo/README.md
@@ -1,7 +1,15 @@
# ndb demo application
# ndb demo applications

## Overview

There are three separate demos:

* app: a Google App Engine application with a set of example uses
* shell: an application that sets up the ndb environment then opens up a python shell for you to interact with.
* task_list: a basic application which runs inside Compute Engine.

## app (App Engine Application)

This demo shows various ways to use ndb. The application consists of serveral
different handlers.
* hello.py: a simple hello world application.
Expand All @@ -13,7 +21,7 @@ different handlers.

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.

## Setup (demo application)
### Setup

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

gcloud config set project <project-id>

## Shell
## shell

1. Follow the instructions below to setup ndb in GCE.

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>.

python demo/shell.py

## Task List

1. Follow the instructions below to setup ndb in GCE.

2. Run the task list application. Don't forget, this application is interacting with the production Datastore of your <project-id>.

python demo/task_list.py

1. First, ensure your environment is setup.
# Setup from your local machine or from Google Compute Engine

1. Install pip

sudo apt-get update
sudo apt-get install python-pip

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.

sudo gcloud components install app-engine-python
export GAE=/usr/local/share/google/google-cloud-sdk/platform/google_appengine

3. Install ndb

pip install --pre ndb

4. Setup your environment.

export DATASTORE_PROJECT_ID=<project-id>
export DATASTORE_USE_PROJECT_ID_AS_APP_ID=true

2. Then, make sure you have authenticated using gcloud.
5. Finally, make sure you have authenticated using gcloud.

gcloud auth login

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>.

python demo/shell.py

17 changes: 17 additions & 0 deletions demo/app/__init__.py
@@ -0,0 +1,17 @@
#
# Copyright 2016 The ndb Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# 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.
183 changes: 183 additions & 0 deletions demo/task_list.py
@@ -0,0 +1,183 @@
#!/usr/bin/python

# Copyright 2015 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START all]
"""Sample for Cloud Datastore using the NDB client library.
This is a command-line task list manager.
From the command line, first setup the necessary environment variables.
export DATASTORE_PROJECT_ID=<my-project-id>
export DATASTORE_USE_PROJECT_ID_AS_APP_ID=true
"""

import ndb
# [START build_service]
# When running outside of App Engine, ndb caching policies should be adjusted.
# The local cache is never evicted, so it should be turned off for any long
# running processes. In order to use memcache, App Engine Remote API must be
# installed. Note that if you are running ndb both inside and outside of
# App Engine, your memcache policies *must* match. Otherwise, calling put may
# not invalidate your cache and App Engine ndb will get stale results.
ndb.get_context().set_cache_policy(False)
ndb.get_context().set_memcache_policy(False)
# [END build_service]


# [START add_entity]
# Define the model we will be using for the tasks.
class Task(ndb.Model):
description = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
done = ndb.BooleanProperty(default=False)


def add_task(description):
"""Adds a new task to the Datastore.
Args:
description: A string description of the task.
Returns:
The key of the entity that was put.
"""
return Task(description=description).put()
# [END add_entity]


# [START update_entity]
@ndb.transactional
def mark_done(task_id):
"""Marks a task as done.
Args:
task_id: The integer id of the task to update.
Raises:
ValueError: if the requested task doesn't exist.
"""
task = Task.get_by_id(task_id)
if task is None:
raise ValueError('Task with id %d does not exist' % task_id)
task.done = True
task.put()
# [END update_entity]


# [START retrieve_entities]
def list_tasks():
"""Lists all the task entities in ascending order of completion time.
Returns:
A list of tasks.
"""
# Querying the tasks without an ancestor is eventually consistent.
return list(Task.query().order(Task.created))
# [END retrieve_entities]


# [START delete_entity]
def delete_task(task_id):
"""Deletes the given task.
Args:
task_id: The integer id of the task to delete.
"""
ndb.Key('Task', task_id).delete()
# [END delete_entity]


# [START format_results]
def format_tasks(tasks):
"""Converts a list of tasks to a list of string representations.
Args:
tasks: A list of the tasks to convert.
Returns:
A list of string formatted tasks.
"""
return ['%d : %s (%s)' % (task.key.id(),
task.description,
('done' if task.done
else 'created %s' % task.created))
for task in tasks]
# [END format_results]


def get_arg(cmds):
"""Accepts a split string command and validates its size.
Args:
cmds: A split command line as a list of strings.
Returns:
The string argument to the command.
Raises:
ValueError: If there is no argument.
"""
if len(cmds) != 2:
raise ValueError('%s needs an argument.' % cmds[0])
return cmds[1]


def handle_command(command):
"""Accepts a string command and performs an action.
Args:
command: the command to run as a string.
"""
try:
cmds = command.split(None, 1)
cmd = cmds[0]
if cmd == 'new':
add_task(get_arg(cmds))
elif cmd == 'done':
mark_done(int(get_arg(cmds)))
elif cmd == 'list':
for task in format_tasks(list_tasks()):
print task
elif cmd == 'delete':
delete_task(int(get_arg(cmds)))
else:
print_usage()
except Exception, e: # pylint: disable=broad-except
print e
print_usage()


def print_usage():
"""Print the usage of our task list command."""
print 'Usage:'
print ''
print ' new <description> Adds a task with a description <description>'
print ' done <task-id> Marks a task as done'
print ' list Lists all tasks by creation time'
print ' delete <task-id> Deletes a task'
print ''


def main():
print 'Cloud Datastore Task List'
print ''
print_usage()
while True:
line = raw_input('> ')
if not line:
break
handle_command(line)

if __name__ == '__main__':
main()
# [END all]

0 comments on commit a263242

Please sign in to comment.