in sample-code/python/main.py [0:0]
def receive_push_messages():
# Pub/Sub push subscriptions deliver messages through regular HTTP POST
# requests, with a JSON body.
request_body = request.get_json(silent=True) # Returns None if not JSON
# This app is intended only to receive Pub/Sub push messages. Reject any
# HTTP POST request that is not a properly formed Pub/Sub push message.
if request_body is None:
print("ERROR: Not JSON") # Log the issue
return "Unsupported Media Type", 415 # Non-2XX notifies error to the sender
if not isinstance(request_body, dict) or "message" not in request_body:
print("ERROR: Not PubSub") # Log the issue
return "Bad Request", 400 # Non-2XX notifies error to the sender
# The request_body seems to a properly formed Pub/Sub message. The message
# itself is a field called "message".
message = request_body["message"]
# The data portion of the message is base64-encoded. Decode it.
data = message.get("data", "") # Empty string if missing
body = base64.b64decode(data).decode("utf-8") # b64decode returns bytes
# Log the decoded data to check if it was correctly received.
print(f"DEBUG: decoded data = '{body}'")
# The body can be any string. For the Pinball game, the body will always
# be a JSON string, usually containing several data fields.
# There are a number of other fields in the message that can convey
# information, some of which are essential to understanding the Pinball
# event.
# See https://cloud.google.com/pubsub/docs for more information on
# the structure and contents of Pub/Sub messages in general.
# See the end of the codelab for specifications of the Pinball message format.
# Determine whether you want the send a message back to the Pinball machine.
# For most events you will not want to do this to avoid spamming the
# machine. You will be given suggestions of events worth responding to,
# such as a completed game with a new high score, or longest duration.
if False: # replace with condition that should trigger a response
result = send_response(
reaction_type="DisplayMessage",
machine_id="GBL:1",
data={"MessageKey": "LUCKY"}
)
print(f"Result of sending message is {result}.")
# Acknowledge the message to prevent retries.
return "OK", 200