Skip to content

Commit a44aa59

Browse files
jwdjjjessiccaa
andauthored
Update pub/sub - appengine push request sample (GoogleCloudPlatform#10747)
* Modify sample for app engine - pub/sub push message * Modify sample for app engine - pub/sub push message * Update main.py Change regional tag - per prefix naming convention * Fix linting error --------- Co-authored-by: Jessica <jesssica@google.com>
1 parent 1693526 commit a44aa59

2 files changed

Lines changed: 44 additions & 2 deletions

File tree

appengine/standard_python3/pubsub/main.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ def index():
6464

6565

6666
# [START gae_standard_pubsub_auth_push]
67-
# [START push]
6867
@app.route("/push-handlers/receive_messages", methods=["POST"])
6968
def receive_messages_handler():
7069
# Verify that the request originates from the application.
@@ -107,9 +106,23 @@ def receive_messages_handler():
107106
return "OK", 200
108107

109108

110-
# [END push]
111109
# [END gae_standard_pubsub_auth_push]
112110

111+
# [START gae_standard_pubsub_push]
112+
@app.route("/pubsub/push", methods=["POST"])
113+
def receive_pubsub_messages_handler():
114+
# Verify that the request originates from the application.
115+
if request.args.get("token", "") != current_app.config["PUBSUB_VERIFICATION_TOKEN"]:
116+
return "Invalid request", 400
117+
118+
envelope = json.loads(request.data.decode("utf-8"))
119+
payload = base64.b64decode(envelope["message"]["data"])
120+
MESSAGES.append(payload)
121+
# Returning any 2xx status indicates successful receipt of the message.
122+
return "OK", 200
123+
124+
# [END gae_standard_pubsub_push]
125+
113126

114127
@app.errorhandler(500)
115128
def server_error(e):

appengine/standard_python3/pubsub/main_test.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,27 @@ def test_push_endpoint(monkeypatch, client, fake_token):
100100
)
101101
assert r.status_code == 200
102102

103+
# Push request without JWT token validation
104+
url = (
105+
"/pubsub/push?token="
106+
+ os.environ["PUBSUB_VERIFICATION_TOKEN"]
107+
)
108+
109+
r = client.post(
110+
url,
111+
data=json.dumps(
112+
{
113+
"message": {
114+
"data": base64.b64encode("Test message".encode("utf-8")).decode(
115+
"utf-8"
116+
)
117+
}
118+
}
119+
),
120+
)
121+
122+
assert r.status_code == 200
123+
103124
# Make sure the message is visible on the home page.
104125
r = client.get("/")
105126
assert r.status_code == 200
@@ -114,3 +135,11 @@ def test_push_endpoint_errors(client):
114135
# invalid token
115136
r = client.post("/push-handlers/receive_messages?token=bad")
116137
assert r.status_code == 400
138+
139+
# no token
140+
r = client.post("/pubsub/push")
141+
assert r.status_code == 400
142+
143+
# invalid token
144+
r = client.post("/pubsub/push?token=bad")
145+
assert r.status_code == 400

0 commit comments

Comments
 (0)