Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add samples for ndb async ops. #311

Merged
merged 1 commit into from
Apr 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions appengine/ndb/async/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## App Engine Datastore NDB Asynchronous Operations Samples

This contains snippets used in the NDB asynchronous operations documentation,
demonstrating various ways to make asynchronous ndb operations.

<!-- auto-doc-link -->
These samples are used on the following documentation page:

> https://cloud.google.com/appengine/docs/python/ndb/async

<!-- end-auto-doc-link -->
35 changes: 35 additions & 0 deletions appengine/ndb/async/app_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2016 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.

from google.appengine.api import users
from google.appengine.ext import ndb
import webapp2


class Account(ndb.Model):
view_counter = ndb.IntegerProperty()


class MyRequestHandler(webapp2.RequestHandler):
def get(self):
acct = Account.get_by_id(users.get_current_user().user_id())
acct.view_counter += 1
future = acct.put_async()

# ...read something else from Datastore...

self.response.out.write('Content of the page')
future.get_result()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're not going to eat that future, can I have it?

(you should do something with the result, log it, maybe?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The text around the sample explains this. Basically it says - you have to call it, so the request will block until the value actually gets written.


app = webapp2.WSGIApplication([('/', MyRequestHandler)])
35 changes: 35 additions & 0 deletions appengine/ndb/async/app_async_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2016 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.

import app_async
import pytest
import webtest


@pytest.fixture
def app(testbed):
return webtest.TestApp(app_async.app)


def test_main(app, testbed, login):
app_async.Account(id='123', view_counter=4).put()

# Log the user in
login(id='123')

response = app.get('/')

assert response.status_int == 200
account = app_async.Account.get_by_id('123')
assert account.view_counter == 5
34 changes: 34 additions & 0 deletions appengine/ndb/async/app_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright 2016 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.

from google.appengine.api import users
from google.appengine.ext import ndb
import webapp2


class Account(ndb.Model):
view_counter = ndb.IntegerProperty()


class MyRequestHandler(webapp2.RequestHandler):
def get(self):
acct = Account.get_by_id(users.get_current_user().user_id())
acct.view_counter += 1
acct.put()

# ...read something else from Datastore...

self.response.out.write('Content of the page')

app = webapp2.WSGIApplication([('/', MyRequestHandler)])
35 changes: 35 additions & 0 deletions appengine/ndb/async/app_sync_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2016 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.

import app_sync
import pytest
import webtest


@pytest.fixture
def app(testbed):
return webtest.TestApp(app_sync.app)


def test_main(app, testbed, login):
app_sync.Account(id='123', view_counter=4).put()

# Log the user in
login(id='123')

response = app.get('/')

assert response.status_int == 200
account = app_sync.Account.get_by_id('123')
assert account.view_counter == 5
2 changes: 2 additions & 0 deletions appengine/ndb/async/app_toplevel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This is in a separate folder to isolate it from the other apps.
This is necessary because the test won't pass when run with the other tests.
39 changes: 39 additions & 0 deletions appengine/ndb/async/app_toplevel/app_toplevel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Copyright 2016 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.

from google.appengine.api import users
from google.appengine.ext import ndb
import webapp2


class Account(ndb.Model):
view_counter = ndb.IntegerProperty()


class MyRequestHandler(webapp2.RequestHandler):
@ndb.toplevel
def get(self):
acct = Account.get_by_id(users.get_current_user().user_id())
acct.view_counter += 1
acct.put_async() # Ignoring the Future this returns

# ...read something else from Datastore...

self.response.out.write('Content of the page')


# This is actually redundant, since the `get` decorator already handles it, but
# for demonstration purposes, you can also make the entire app toplevel with
# the following.
app = ndb.toplevel(webapp2.WSGIApplication([('/', MyRequestHandler)]))
35 changes: 35 additions & 0 deletions appengine/ndb/async/app_toplevel/app_toplevel_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2016 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.

import app_toplevel
import pytest
import webtest


@pytest.fixture
def app(testbed):
return webtest.TestApp(app_toplevel.app)


def test_main(app, testbed, login):
app_toplevel.Account(id='123', view_counter=4).put()

# Log the user in
login(id='123')

response = app.get('/')

assert response.status_int == 200
account = app_toplevel.Account.get_by_id('123')
assert account.view_counter == 5
Empty file.
101 changes: 101 additions & 0 deletions appengine/ndb/async/guestbook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Copyright 2016 Google Inc. All rights reserved.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I see another guestbook I'm going to lose it.

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

from google.appengine.api import users
from google.appengine.ext import ndb
import webapp2


class Guestbook(ndb.Model):
content = ndb.StringProperty()
post_date = ndb.DateTimeProperty(auto_now_add=True)


class Account(ndb.Model):
email = ndb.StringProperty()
nickname = ndb.StringProperty()

def nick(self):
return self.nickname or self.email # Whichever is non-empty


class Message(ndb.Model):
text = ndb.StringProperty()
when = ndb.DateTimeProperty(auto_now_add=True)
author = ndb.KeyProperty(kind=Account) # references Account


class MainPage(webapp2.RequestHandler):
def get(self):
if self.request.path == '/guestbook':
if self.request.get('async'):
self.get_guestbook_async()
else:
self.get_guestbook_sync()
elif self.request.path == '/messages':
if self.request.get('async'):
self.get_messages_async()
else:
self.get_messages_sync()

def get_guestbook_sync(self):
uid = users.get_current_user().user_id()
acct = Account.get_by_id(uid) # I/O action 1
qry = Guestbook.query().order(-Guestbook.post_date)
recent_entries = qry.fetch(10) # I/O action 2

# ...render HTML based on this data...
self.response.out.write('<html><body>{}</body></html>'.format(''.join(
'<p>{}</p>'.format(entry.content) for entry in recent_entries)))

return acct, qry

def get_guestbook_async(self):
uid = users.get_current_user().user_id()
acct_future = Account.get_by_id_async(uid) # Start I/O action #1
qry = Guestbook.query().order(-Guestbook.post_date)
recent_entries_future = qry.fetch_async(10) # Start I/O action #2
acct = acct_future.get_result() # Complete #1
recent_entries = recent_entries_future.get_result() # Complete #2

# ...render HTML based on this data...
self.response.out.write('<html><body>{}</body></html>'.format(''.join(
'<p>{}</p>'.format(entry.content) for entry in recent_entries)))

return acct, recent_entries

def get_messages_sync(self):
qry = Message.query().order(-Message.when)
for msg in qry.fetch(20):
acct = msg.author.get()
self.response.out.write(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use format.

'<p>On {}, {} wrote:'.format(msg.when, acct.nick()))
self.response.out.write('<p>{}'.format(msg.text))

def get_messages_async(self):
@ndb.tasklet
def callback(msg):
acct = yield msg.author.get_async()
raise ndb.Return('On {}, {} wrote:\n{}'.format(
msg.when, acct.nick(), msg.text))

qry = Message.query().order(-Message.when)
outputs = qry.map(callback, limit=20)
for output in outputs:
self.response.out.write('<p>{}</p>'.format(output))


app = webapp2.WSGIApplication([
('/.*', MainPage),
], debug=True)
Loading