Skip to content

New sample: Cloud ndb with redis cache #4477

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

Merged
merged 5 commits into from
Aug 15, 2020
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
33 changes: 33 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
## App Engine Datastore NDB Overview Sample

[![Open in Cloud Shell][shell_img]][shell_link]

[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=appengine/standard/migration/ndb/overview/README.md

This is a sample app for Google App Engine that demonstrates how to replace
use of the [Datastore NDB Python API](https://cloud.google.com/appengine/docs/python/ndb/)
with the [Google Cloud NDB library](https://googleapis.dev/python/python-ndb/latest/index.html).
This library can be used not only on App Engine, but also other Python 3
platforms.

This sample also uses
[Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/redis-overview)
caching to improve NDB performance in some situations.

Prior to deploying this sample, a
[serverless VPC connector](https://cloud.google.com/vpc/docs/configure-serverless-vpc-access)
must be created and then a
[Memorystore for Redis instance](https://cloud.google.com/memorystore/docs/redis/quickstart-console)
on the same VPC. The IP address and port number of the Redis instance, and
the name of the VPC connector should be entered in either app.yaml
(for Python 2.7) or app3.yaml (for Python 3).

To deploy and run this sample in App Engine standard for Python 2.7:

pip install -t lib -r requirements.txt
gcloud app deploy app.yaml index.yaml

To deploy and run this sample in App Engine standard for Python 3.7:

gcloud app deploy app3.yaml index.yaml
28 changes: 28 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This file specifies your Python application's runtime configuration
# including URL routing, versions, static file uploads, etc. See
# https://developers.google.com/appengine/docs/python/config/appconfig
# for details.

runtime: python27
api_version: 1
threadsafe: yes

# Handlers define how to route requests to your application.
handlers:
# This handler tells app engine how to route requests to a WSGI application.
# The script value is in the format <path.to.module>.<wsgi_application>
# where <wsgi_application> is a WSGI application object.
- url: .* # This regex directs all routes to main.app
script: main.app

libraries:
- name: setuptools
version: 36.6.0
- name: grpcio
version: 1.0.0

env_variables:
REDIS_CACHE_URL: 'redis://<REDIS_HOST>:<REDIS_PORT>'

vpc_access_connector:
name: 'projects/<PROJECT_ID>/locations/<REGION>/connectors/<CONNECTOR_NAME>'
7 changes: 7 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/app3.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
runtime: python38

env_variables:
REDIS_CACHE_URL: 'redis://<REDIS_HOST>:<REDIS_PORT>'

vpc_access_connector:
name: 'projects/<PROJECT_ID>/locations/<REGION>/connectors/<CONNECTOR_NAME>'
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import pkg_resources
from google.appengine.ext import vendor

# Set path to your libraries folder.
path = 'lib'
# Add libraries installed in the path folder.
vendor.add(path)
# Add libraries to pkg_resources working set to find the distribution.
pkg_resources.working_set.add_entry(path)
Binary file not shown.
17 changes: 17 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/index.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
indexes:

# AUTOGENERATED

# This index.yaml is automatically updated whenever the dev_appserver
# detects that a new type of query is run. If you want to manage the
# index.yaml file manually, remove the above marker line (the line
# saying "# AUTOGENERATED"). If you want to manage some indexes
# manually, move them above the marker line. The index.yaml file is
# automatically uploaded to the admin console when you next deploy
# your application using appcfg.py.

- kind: Greeting
ancestor: yes
properties:
- name: date
direction: desc
89 changes: 89 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Copyright 2020 Google LLC
#
# 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]
from flask import Flask, redirect, render_template, request
from google.cloud import ndb
import logging

try:
from urllib import urlencode
except Exception:
from urllib.parse import urlencode

app = Flask(__name__)
client = ndb.Client()

try:
global_cache = ndb.RedisCache.from_environment()
except Exception:
logging.warning('Redis not available.')
global_cache = None


# [START greeting]
class Greeting(ndb.Model):
"""Models an individual Guestbook entry with content and date."""
content = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
# [END greeting]

# [START query]
with client.context(global_cache=global_cache):
@classmethod
def query_book(cls, ancestor_key):
return cls.query(ancestor=ancestor_key).order(-cls.date)


@app.route('/', methods=['GET'])
def display_guestbook():
guestbook_name = request.args.get('guestbook_name', '')
print('GET guestbook name is {}'.format(guestbook_name))
with client.context(global_cache=global_cache):
ancestor_key = ndb.Key("Book", guestbook_name or "*notitle*")
greetings = Greeting.query_book(ancestor_key).fetch(20)
# [END query]

greeting_blockquotes = [greeting.content for greeting in greetings]
return render_template(
'index.html',
greeting_blockquotes=greeting_blockquotes,
guestbook_name=guestbook_name
)


# [START submit]
@app.route('/sign', methods=['POST'])
def update_guestbook():
# We set the parent key on each 'Greeting' to ensure each guestbook's
# greetings are in the same entity group.
guestbook_name = request.form.get('guestbook_name', '')
print('Guestbook name from the form: {}'.format(guestbook_name))

with client.context(global_cache=global_cache):
print('Guestbook name from the URL: {}'.format(guestbook_name))
greeting = Greeting(
parent=ndb.Key("Book", guestbook_name or "*notitle*"),
content=request.form.get('content', None)
)
greeting.put()
# [END submit]

return redirect('/?' + urlencode({'guestbook_name': guestbook_name}))


if __name__ == '__main__':
# This is used when running locally.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END all]
28 changes: 28 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/main_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# 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.

import pytest


@pytest.fixture
def app():
import main
main.app.testing = True
return main.app.test_client()


@pytest.mark.skip
def test_app(app):
response = app.get('/')
assert response.status_code == 200
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==4.6.11; python_version < '3.0'
5 changes: 5 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Newer versions of rsa module are incompatible with Python 2.7
rsa==4.5; python_version < '3'
googleapis_common_protos
google-cloud-ndb
flask==1.1.2
30 changes: 30 additions & 0 deletions appengine/standard/migration/ndb/redis_cache/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!doctype html>
<html>
<head>
<title>Guestbook</title>
</head>

<body>
{% for greeting in greeting_blockquotes %}
<blockquote>{{ greeting }}</blockquote>
{% endfor %}

<form action="/sign" method="post">
<div>
<textarea name="content" rows="3" cols="60"></textarea>
</div>
<div>
<input type="submit" value="Sign Guestbook" />
<input type="hidden" name="guestbook_name" value="{{ guestbook_name }}"/>
</div>
</form>

<hr>

<form action="/" method="GET">
Guestbook name:
<input name="guestbook_name" value="{{guestbook_name}}" />
<input type="submit" value="switch" />
</form>
</body>
</html >