Python Google Cloud Pub/Sub sample for Google App Engine Standard Environment
Before you can run or deploy the sample, you will need to do the following:
Enable the Cloud Pub/Sub API in the Google Developers Console.
Create a topic and subscription.
$ gcloud pubsub topics create [your-topic-name] $ gcloud pubsub subscriptions create [your-subscription-name] \ --topic [your-topic-name] \ --push-endpoint \ https://[your-app-id].appspot.com/_ah/push-handlers/receive_messages/token=[your-token] \ --ack-deadline 30
Update the environment variables in
Refer to the top-level README for instructions on running and deploying.
When running locally, you can use the Google Cloud SDK to provide authentication to use Google Cloud APIs:
$ gcloud init
Install dependencies, preferably with a virtualenv:
$ virtualenv env $ source env/bin/activate $ pip install -r requirements.txt
Then set environment variables before starting your application:
$ export GOOGLE_CLOUD_PROJECT=[your-project-name] $ export PUBSUB_VERIFICATION_TOKEN=[your-verification-token] $ export PUBSUB_TOPIC=[your-topic] $ python main.py
Simulating push notifications
The application can send messages locally, but it is not able to receive push messages locally. You can, however, simulate a push message by making an HTTP request to the local push notification endpoint. There is an included
sample_message.json. You can use
curl or httpie to POST this:
$ curl -i --data @sample_message.json ":8080/_ah/push-handlers/receive_messages?token=[your-token]"
$ http POST ":8080/_ah/push-handlers/receive_messages?token=[your-token]" < sample_message.json
HTTP/1.0 200 OK Content-Length: 2 Content-Type: text/html; charset=utf-8 Date: Mon, 10 Aug 2015 17:52:03 GMT Server: Werkzeug/0.10.4 Python/2.7.10 OK
After the request completes, you can refresh
localhost:8080 and see the message in the list of received messages.
Running on App Engine
gcloud app deploy app.yaml
You can now access the application at
https://your-app-id.appspot.com. You can use the form to submit messages, but it's non-deterministic which instance of your application will receive the notification. You can send multiple messages and refresh the page to see the received message.