diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5910ce6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +ARG PYTHON_VERSION=3.12.2 +FROM python:${PYTHON_VERSION}-slim as base + +WORKDIR /app + +COPY . . + +RUN python3 -m pip install -r requirements.txt + +EXPOSE 8080 + + +CMD gunicorn 'counter-service:app' --bind=0.0.0.0:8080 diff --git a/counter-service.py b/counter-service.py new file mode 100644 index 0000000..e46e741 --- /dev/null +++ b/counter-service.py @@ -0,0 +1,61 @@ +from flask import Flask, request, jsonify +import os + +app = Flask(__name__) + +# define path to file to store the counter +COUNTER_FILE = "./data/counter.txt" + +def read_counter(): + """ + reads the counter file for the counter value. If the file doesnot + exist it returns 0. + + Returns: + int: The current value of the counter + """ + + if os.path.exists(COUNTER_FILE): + with open(COUNTER_FILE, "r") as f: + return int(f.read().strip()) + else: + return 0 + +def update_counter(counter): + """ + updates the counter file with the passed counter argument + + Args: + counter (int): The new counter value to be stored in the file + + """ + with open(COUNTER_FILE,"w") as f: + f.write(str(counter)) + +@app.route('/', methods=['GET','POST']) +def handle_request(): + + counter = read_counter() + + if request.method == 'POST': + counter+=1 + update_counter(counter) + return f"updated the counter value. new value is ${counter}" + else: + return f"current posts request count is ${counter}" + +@app.route('/health', methods=['GET']) +def health_check(): + + try: + read_counter() + return jsonify({"status": "healthy"}), 200 + except Exception as e: + return jsonify({"status": "unhealthy", "reson": str(e)}), 500 + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=8080, debug=False) + + + + diff --git a/data/counter.txt b/data/counter.txt new file mode 100644 index 0000000..56a6051 --- /dev/null +++ b/data/counter.txt @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2802ff3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +blinker==1.8.1 +click==8.1.7 +Flask==3.0.3 +gunicorn==22.0.0 +itsdangerous==2.2.0 +Jinja2==3.1.4 +MarkupSafe==2.1.5 +packaging==24.0 +Werkzeug==3.0.3