|
| 1 | +# Copyright 2023 Google LLC. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START eventarc_storage_cloudevent_server] |
| 16 | +import os |
| 17 | + |
| 18 | +from cloudevents.http import from_http |
| 19 | + |
| 20 | +from flask import Flask, request |
| 21 | + |
| 22 | +from google.events.cloud.storage import StorageObjectData |
| 23 | + |
| 24 | + |
| 25 | +app = Flask(__name__) |
| 26 | +# [END eventarc_storage_cloudevent_server] |
| 27 | + |
| 28 | + |
| 29 | +# [START eventarc_storage_cloudevent_handler] |
| 30 | +@app.route("/", methods=["POST"]) |
| 31 | +def index(): |
| 32 | + event = from_http(request.headers, request.get_data()) |
| 33 | + |
| 34 | + # Gets the GCS bucket name from the CloudEvent data |
| 35 | + # Example: "storage.googleapis.com/projects/_/buckets/my-bucket" |
| 36 | + try: |
| 37 | + storage_obj = StorageObjectData(event.data) |
| 38 | + gcs_object = os.path.join(storage_obj.bucket, storage_obj.name) |
| 39 | + update_time = storage_obj.updated |
| 40 | + return ( |
| 41 | + f"Cloud Storage object changed: {gcs_object}" |
| 42 | + + f" updated at {update_time}", |
| 43 | + 200, |
| 44 | + ) |
| 45 | + except ValueError as e: |
| 46 | + return (f"Failed to parse event data: {e}", 400) |
| 47 | + |
| 48 | + |
| 49 | +# [END eventarc_storage_cloudevent_handler] |
| 50 | + |
| 51 | + |
| 52 | +# [START eventarc_storage_cloudevent_server] |
| 53 | +if __name__ == "__main__": |
| 54 | + app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080))) |
| 55 | +# [END eventarc_storage_cloudevent_server] |
0 commit comments