├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── appengine-push
├── README.md
├── app.yaml
├── appengine_config.py
├── constants.py
├── js
│ └── pubsub.js
├── main.py
├── pubsub_utils.py
├── requirements.txt
├── templates
│ └── pubsub.html
└── test_deploy.py
├── client-secret.json.enc
├── cmdline-pull
├── .gitignore
├── README.md
├── pubsub_sample.py
├── requirements.txt
└── test_pubsub_sample.py
├── gce-cmdline-publisher
├── README.md
└── traffic_pubsub_generator.py
├── grpc
├── README.md
├── pubsub_sample.py
└── requirements.txt
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | # Copied from
2 | # https://github.com/github/gitignore/blob/master/Python.gitignore
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | *.py[cod]
7 |
8 | # C extensions
9 | *.so
10 |
11 | # Distribution / packaging
12 | .Python
13 | env/
14 | build/
15 | develop-eggs/
16 | dist/
17 | eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # Installer logs
28 | pip-log.txt
29 | pip-delete-this-directory.txt
30 |
31 | # Unit test / coverage reports
32 | htmlcov/
33 | .tox/
34 | .coverage
35 | .cache
36 | nosetests.xml
37 | coverage.xml
38 |
39 | # Translations
40 | *.mo
41 | *.pot
42 |
43 | # Django stuff:
44 | *.log
45 |
46 | # Sphinx documentation
47 | docs/_build/
48 | client-secret.json
49 |
50 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: python
3 | branches:
4 | only:
5 | - master
6 |
7 | cache:
8 | directories:
9 | - ${HOME}/gcloud/
10 |
11 | install:
12 | - pip install tox
13 |
14 | env:
15 | globals:
16 | - PATH=${PATH}:${HOME}/gcloud/google-cloud-sdk/bin
17 | - CLOUDSDK_CORE_DISABLE_PROMPTS=1
18 |
19 | before_install:
20 | - openssl aes-256-cbc -K $encrypted_a53bb0208314_key -iv $encrypted_a53bb0208314_iv -in client-secret.json.enc -out client-secret.json -d
21 | - if [ ! -d ${HOME}/gcloud/google-cloud-sdk ]; then
22 | mkdir -p ${HOME}/gcloud &&
23 | wget https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz --directory-prefix=${HOME}/gcloud &&
24 | cd ${HOME}/gcloud &&
25 | tar xzf google-cloud-sdk.tar.gz &&
26 | ./google-cloud-sdk/install.sh --usage-reporting false --path-update false --command-completion false &&
27 | cd ${TRAVIS_BUILD_DIR};
28 | fi
29 | - gcloud -q components update app
30 | - if [ -a client-secret.json ]; then
31 | gcloud auth activate-service-account --key-file client-secret.json;
32 | fi
33 | - gcloud config set project cloud-pubsub-sample-test
34 | - mkdir -p appengine-push/lib
35 | - pip install -t appengine-push/lib -r appengine-push/requirements.txt
36 | - gcloud -q app deploy --project cloud-pubsub-sample-test --version=py appengine-push/app.yaml
37 |
38 | script:
39 | - tox
40 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Contributor License Agreements
2 | ------------------------------
3 |
4 | Before we can accept your pull requests you'll need to sign a Contributor License Agreement (CLA):
5 |
6 | * If you are an individual writing original source code and you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual).
7 |
8 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate>).
9 |
10 | You can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests.
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Cloud Pub/Sub samples for Python
2 |
3 | ## Overview
4 |
5 | This repository contains several samples for Cloud Pub/Sub service
6 | with Python.
7 |
8 | - appengine-push
9 |
10 | A sample for push subscription running on [Google App Engine][1].
11 |
12 | - cmdline-pull
13 |
14 | A command line sample for pull subscription.
15 |
16 | - gce-cmdline-publisher
17 |
18 | A Python command-line script that publishes to a topic using data from a large traffic sensor dataset.
19 |
20 | ## Run tests
21 |
22 | Here are instructions to run the tests. You need a cloud project with
23 | Cloud Pub/Sub enabled.
24 |
25 | ```bash
26 | $ pip install tox
27 | $ export GOOGLE_APPLICATION_CREDENTIALS=your-service-account-json-file
28 | $ export TEST_PROJECT_ID={YOUR_PROJECT_ID}
29 | $ tox
30 | ```
31 |
32 | ## Licensing
33 |
34 | See LICENSE
35 |
36 | [1]: https://developers.google.com/appengine/
37 |
--------------------------------------------------------------------------------
/appengine-push/README.md:
--------------------------------------------------------------------------------
1 | # cloud-pubsub-samples-python
2 |
3 | ## appengine-push
4 |
5 | Note: The push endpoints don't work with the App Engine's local
6 | devserver. The push notifications will go to an HTTP URL on the App
7 | Engine server even when you run this sample locally. So we recommend
8 | you deploy and run the app on App Engine.
9 | TODO(tmatsuo): Better implementation for devserver.
10 |
11 | ## Register your application
12 |
13 | - Go to
14 | [Google Developers Console](https://console.developers.google.com/project)
15 | and create a new project. This will automatically enable an App
16 | Engine application with the same ID as the project.
17 |
18 | - Enable the "Google Cloud Pub/Sub" API under "APIs & auth > APIs."
19 |
20 | - For local development also follow the instructions below.
21 |
22 | - Go to "Credentials" and create a new Service Account.
23 |
24 | - Select "Generate new JSON key", then download a new JSON file.
25 |
26 | - Set the following environment variable.
27 |
28 | GOOGLE_APPLICATION_CREDENTIALS: the file path to the downloaded JSON file.
29 |
30 | ## Prerequisites
31 |
32 | - Install Python-2.7, pip-6.0.0 or higher and App Engine Python SDK.
33 | We recommend you install
34 | [Cloud SDK](https://developers.google.com/cloud/sdk/) rather than
35 | just installing App Engine SDK.
36 |
37 | - Install Google API client library for python into 'lib' directory by:
38 |
39 | ```
40 | $ pip install -t lib -r requirements.txt
41 | ```
42 |
43 | ## Configuration
44 |
45 | - Edit constants.py
46 | - Replace '{AN_UNIQUE_TOKEN}' with an arbitrary secret string of
47 | your choice to protect the endpoint from abuse.
48 |
49 | ## Deploy the application to App Engine
50 |
51 | ```
52 | $ appcfg.py --oauth2 update -A your-application-id .
53 | ```
54 |
55 | or you can use gcloud SDK
56 |
57 | ```
58 | $ gcloud app deploy
59 | ```
60 |
61 | Then access the following URL:
62 | https://{your-application-id}.appspot.com/
63 |
64 | ## Run the application locally
65 |
66 | ```
67 | $ dev_appserver.py -A your-application-id .
68 | ```
69 |
--------------------------------------------------------------------------------
/appengine-push/app.yaml:
--------------------------------------------------------------------------------
1 | runtime: python27
2 | api_version: 1
3 | threadsafe: true
4 |
5 | handlers:
6 | - url: /js
7 | static_dir: js
8 | - url: /_ah/push-handlers/.*
9 | script: main.APPLICATION
10 | login: admin
11 | - url: /.*
12 | script: main.APPLICATION
13 |
14 | libraries:
15 | - name: jinja2
16 | version: latest
17 | - name: webapp2
18 | version: latest
19 | - name: pycrypto
20 | version: latest
21 | - name: ssl
22 | version: latest
23 |
--------------------------------------------------------------------------------
/appengine-push/appengine_config.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright 2014 Google Inc. 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 | """Cloud Pub/Sub sample application config."""
18 |
19 | from google.appengine.ext import vendor
20 |
21 | vendor.add('lib')
22 |
--------------------------------------------------------------------------------
/appengine-push/constants.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright 2014 Google Inc. 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 | """Cloud Pub/Sub sample application constants."""
18 |
19 | SUBSCRIPTION_UNIQUE_TOKEN = '{AN-UNIQUE-TOKEN}'
20 |
--------------------------------------------------------------------------------
/appengine-push/js/pubsub.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | var pubsub = pubsub || angular.module('pubsub', []);
5 |
6 | /**
7 | * PubsubController.
8 | *
9 | * @NgInject
10 | */
11 | pubsub.PubsubController = function($http, $log, $timeout) {
12 | this.promise = null;
13 | this.logger = $log;
14 | this.http = $http;
15 | this.timeout = $timeout;
16 | this.interval = 1;
17 | this.isAutoUpdating = true;
18 | this.failCount = 0;
19 | this.fetchMessages();
20 | };
21 |
22 | pubsub.PubsubController.MAX_FAILURE_COUNT = 3;
23 |
24 | pubsub.PubsubController.TIMEOUT_MULTIPLIER = 1000;
25 |
26 | /**
27 | * Toggles the auto update flag.
28 | */
29 | pubsub.PubsubController.prototype.toggleAutoUpdate = function() {
30 | this.isAutoUpdating = !this.isAutoUpdating;
31 | if (this.isAutoUpdating) {
32 | this.logger.info('Start fetching.');
33 | this.fetchMessages();
34 | } else if (this.promise !== null) {
35 | this.logger.info('Cancel the promise.');
36 | this.timeout.cancel(this.promise);
37 | this.promise = null;
38 | }
39 | };
40 |
41 | /**
42 | * Sends a message
43 | *
44 | * @param {string} message
45 | */
46 | pubsub.PubsubController.prototype.sendMessage = function(message) {
47 | var self = this;
48 | self.http({
49 | method: 'POST',
50 | url: '/send_message',
51 | data: 'message=' + encodeURIComponent(message),
52 | headers: {'Content-Type': 'application/x-www-form-urlencoded'}
53 | }).success(function(data, status) {
54 | self.message = null;
55 | }).error(function(data, status) {
56 | self.logger.error('Failed to send the message. Status: ' + status + '.');
57 | });
58 | };
59 |
60 | /**
61 | * Continuously fetches messages from the server.
62 | */
63 | pubsub.PubsubController.prototype.fetchMessages = function() {
64 | var self = this;
65 | self.http.get('/fetch_messages')
66 | .success(function(data, status) {
67 | self.messages = data;
68 | self.failCount = 0;
69 | })
70 | .error(function(data, status) {
71 | self.logger.error('Failed to receive the messages. Status: ' +
72 | status + '.');
73 | self.failCount += 1;
74 | });
75 | if (self.failCount < pubsub.PubsubController.MAX_FAILURE_COUNT) {
76 | if (self.isAutoUpdating) {
77 | self.promise = self.timeout(
78 | function() { self.fetchMessages(); },
79 | self.interval * pubsub.PubsubController.TIMEOUT_MULTIPLIER);
80 | }
81 | } else {
82 | self.errorNotice = 'Maximum failure count reached, ' +
83 | 'so stopped fetching messages.';
84 | self.logger.error(self.errorNotice);
85 | self.isAutoUpdating = false;
86 | self.failCount = 0;
87 | }
88 | };
89 |
--------------------------------------------------------------------------------
/appengine-push/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright 2014 Google Inc. 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 | """Cloud Pub/Sub sample application."""
18 |
19 |
20 | import base64
21 | import json
22 | import logging
23 | import re
24 | import urllib
25 |
26 | from apiclient import errors
27 | from google.appengine.api import memcache
28 | from google.appengine.ext import ndb
29 |
30 | import jinja2
31 |
32 | import webapp2
33 |
34 | import constants
35 | import pubsub_utils
36 |
37 |
38 | JINJA2 = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'),
39 | extensions=['jinja2.ext.autoescape'],
40 | variable_start_string='((',
41 | variable_end_string='))',
42 | autoescape=True)
43 |
44 | MAX_ITEM = 20
45 |
46 | MESSAGE_CACHE_KEY = 'messages_key'
47 |
48 |
49 | class PubSubMessage(ndb.Model):
50 | """A model stores pubsub message and the time when it arrived."""
51 | message = ndb.StringProperty()
52 | created_at = ndb.DateTimeProperty(auto_now_add=True)
53 |
54 |
55 | class InitHandler(webapp2.RequestHandler):
56 | """Initializes the Pub/Sub resources."""
57 | def __init__(self, request=None, response=None):
58 | """Calls the constructor of the super and does the local setup."""
59 | super(InitHandler, self).__init__(request, response)
60 | self.client = pubsub_utils.get_client()
61 | self._setup_topic()
62 | self._setup_subscription()
63 |
64 | def _setup_topic(self):
65 | """Creates a topic if it does not exist."""
66 | topic_name = pubsub_utils.get_full_topic_name()
67 | try:
68 | self.client.projects().topics().get(
69 | topic=topic_name).execute()
70 | except errors.HttpError as e:
71 | if e.resp.status == 404:
72 | self.client.projects().topics().create(
73 | name=topic_name, body={}).execute()
74 | else:
75 | logging.exception(e)
76 | raise
77 |
78 | def _setup_subscription(self):
79 | """Creates a subscription if it does not exist."""
80 | subscription_name = pubsub_utils.get_full_subscription_name()
81 | try:
82 | self.client.projects().subscriptions().get(
83 | subscription=subscription_name).execute()
84 | except errors.HttpError as e:
85 | if e.resp.status == 404:
86 | body = {
87 | 'topic': pubsub_utils.get_full_topic_name(),
88 | 'pushConfig': {
89 | 'pushEndpoint': pubsub_utils.get_app_endpoint_url()
90 | }
91 | }
92 | self.client.projects().subscriptions().create(
93 | name=subscription_name, body=body).execute()
94 | else:
95 | logging.exception(e)
96 | raise
97 |
98 | def get(self):
99 | """Shows an HTML form."""
100 | template = JINJA2.get_template('pubsub.html')
101 | endpoint_url = re.sub('token=[^&]*', 'token=REDACTED',
102 | pubsub_utils.get_app_endpoint_url())
103 | context = {
104 | 'project': pubsub_utils.get_project_id(),
105 | 'topic': pubsub_utils.get_app_topic_name(),
106 | 'subscription': pubsub_utils.get_app_subscription_name(),
107 | 'subscriptionEndpoint': endpoint_url
108 | }
109 | self.response.write(template.render(context))
110 |
111 |
112 | class FetchMessages(webapp2.RequestHandler):
113 | """A handler returns messages."""
114 | def get(self):
115 | """Returns recent messages as a json."""
116 | messages = memcache.get(MESSAGE_CACHE_KEY)
117 | if not messages:
118 | messages = PubSubMessage.query().order(
119 | -PubSubMessage.created_at).fetch(MAX_ITEM)
120 | memcache.add(MESSAGE_CACHE_KEY, messages)
121 | self.response.headers['Content-Type'] = ('application/json;'
122 | ' charset=UTF-8')
123 | self.response.write(
124 | json.dumps(
125 | [message.message for message in messages]))
126 |
127 |
128 | class SendMessage(webapp2.RequestHandler):
129 | """A handler publishes the given message."""
130 | def post(self):
131 | """Publishes the message via the Pub/Sub API."""
132 | client = pubsub_utils.get_client()
133 | message = self.request.get('message')
134 | if message:
135 | topic_name = pubsub_utils.get_full_topic_name()
136 | body = {
137 | 'messages': [{
138 | 'data': base64.b64encode(message.encode('utf-8'))
139 | }]
140 | }
141 | client.projects().topics().publish(
142 | topic=topic_name, body=body).execute()
143 | self.response.status = 204
144 |
145 |
146 | class ReceiveMessage(webapp2.RequestHandler):
147 | """A handler for push subscription endpoint.."""
148 | def post(self):
149 | if constants.SUBSCRIPTION_UNIQUE_TOKEN != self.request.get('token'):
150 | self.response.status = 404
151 | return
152 |
153 | # Store the message in the datastore.
154 | logging.debug('Post body: {}'.format(self.request.body))
155 | message = json.loads(urllib.unquote(self.request.body).rstrip('='))
156 | message_body = base64.b64decode(str(message['message']['data']))
157 | pubsub_message = PubSubMessage(message=message_body)
158 | pubsub_message.put()
159 |
160 | # Invalidate the cache
161 | memcache.delete(MESSAGE_CACHE_KEY)
162 | self.response.status = 200
163 |
164 |
165 | APPLICATION = webapp2.WSGIApplication(
166 | [
167 | ('/', InitHandler),
168 | ('/fetch_messages', FetchMessages),
169 | ('/send_message', SendMessage),
170 | ('/_ah/push-handlers/receive_message', ReceiveMessage),
171 | ], debug=True)
172 |
--------------------------------------------------------------------------------
/appengine-push/pubsub_utils.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright 2014 Google Inc. 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 | """Utility module for this Pub/Sub sample."""
18 |
19 | import os
20 | import threading
21 |
22 | from google.appengine.api import app_identity
23 | from google.appengine.api import memcache
24 | from google.appengine.api import modules
25 |
26 | from googleapiclient import discovery
27 | import httplib2
28 | from oauth2client.client import GoogleCredentials
29 |
30 | import constants
31 |
32 |
33 | APPLICATION_NAME = "google-cloud-pubsub-appengine-sample/1.0"
34 |
35 | PUBSUB_SCOPES = ["https://www.googleapis.com/auth/pubsub"]
36 |
37 |
38 | client_store = threading.local()
39 |
40 |
41 | def is_devserver():
42 | """Check if the app is running on devserver or not."""
43 | return os.getenv('SERVER_SOFTWARE', '').startswith('Dev')
44 |
45 |
46 | def get_client():
47 | """Creates Pub/Sub client and returns it."""
48 | if not hasattr(client_store, 'client'):
49 | client_store.client = get_client_from_credentials(
50 | GoogleCredentials.get_application_default())
51 | return client_store.client
52 |
53 |
54 | def get_client_from_credentials(credentials):
55 | """Creates Pub/Sub client from a given credentials and returns it."""
56 | if credentials.create_scoped_required():
57 | credentials = credentials.create_scoped(PUBSUB_SCOPES)
58 |
59 | http = httplib2.Http(memcache)
60 | credentials.authorize(http)
61 |
62 | return discovery.build('pubsub', 'v1', http=http)
63 |
64 |
65 | def get_full_topic_name():
66 | return 'projects/{}/topics/{}'.format(
67 | get_project_id(), get_app_topic_name())
68 |
69 |
70 | def get_full_subscription_name():
71 | return 'projects/{}/subscriptions/{}'.format(
72 | get_project_id(), get_app_subscription_name())
73 |
74 |
75 | def get_app_topic_name():
76 | return 'topic-pubsub-api-appengine-sample-python'
77 |
78 |
79 | def get_app_subscription_name():
80 | return 'subscription-python-{}'.format(get_project_id())
81 |
82 |
83 | def get_app_endpoint_url():
84 | return ('https://{}-dot-{}.appspot.com/_ah/push-handlers'
85 | '/receive_message?token={}').format(
86 | get_current_version(), get_project_id(),
87 | constants.SUBSCRIPTION_UNIQUE_TOKEN)
88 |
89 |
90 | def get_project_id():
91 | return app_identity.get_application_id()
92 |
93 |
94 | def get_current_version():
95 | return modules.get_current_version_name()
96 |
--------------------------------------------------------------------------------
/appengine-push/requirements.txt:
--------------------------------------------------------------------------------
1 | google-api-python-client
2 |
--------------------------------------------------------------------------------
/appengine-push/templates/pubsub.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |