|
| 1 | +# Copyright 2019 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 run_broken_service] |
| 16 | +from flask import Flask |
| 17 | +import json |
| 18 | +import os |
| 19 | +import sys |
| 20 | + |
| 21 | +app = Flask(__name__) |
| 22 | + |
| 23 | + |
| 24 | +@app.route("/", methods=["GET"]) |
| 25 | +def index(): |
| 26 | + print("hello: received request.") |
| 27 | + |
| 28 | + # [START run_broken_service_problem] |
| 29 | + NAME = os.getenv("NAME") |
| 30 | + |
| 31 | + if not NAME: |
| 32 | + print("Environment validation failed.") |
| 33 | + raise Exception("Missing required service parameter.") |
| 34 | + # [END run_broken_service_problem] |
| 35 | + |
| 36 | + # Flush the stdout to avoid log buffering. |
| 37 | + sys.stdout.flush() |
| 38 | + |
| 39 | + return f"Hello {NAME}" |
| 40 | +# [END run_broken_service] |
| 41 | + |
| 42 | + |
| 43 | +@app.route("/improved", methods=["GET"]) |
| 44 | +def improved(): |
| 45 | + print("hello: received request.") |
| 46 | + |
| 47 | + # [START run_broken_service_upgrade] |
| 48 | + NAME = os.getenv("NAME") |
| 49 | + |
| 50 | + if not NAME: |
| 51 | + NAME = "World" |
| 52 | + error_message = { |
| 53 | + "severity": "WARNING", |
| 54 | + "message": f"NAME not set, default to {NAME}", |
| 55 | + } |
| 56 | + print(json.dumps(error_message)) |
| 57 | + # [END run_broken_service_upgrade] |
| 58 | + |
| 59 | + # Flush the stdout to avoid log buffering. |
| 60 | + sys.stdout.flush() |
| 61 | + |
| 62 | + return f"Hello {NAME}" |
| 63 | + |
| 64 | + |
| 65 | +# [START run_broken_service] |
| 66 | +if __name__ == "__main__": |
| 67 | + PORT = int(os.getenv("PORT")) if os.getenv("PORT") else 8080 |
| 68 | + |
| 69 | + # This is used when running locally. Gunicorn is used to run the |
| 70 | + # application on Cloud Run. See entrypoint in Dockerfile. |
| 71 | + app.run(host="127.0.0.1", port=PORT, debug=True) |
| 72 | +# [END run_broken_service] |
0 commit comments