diff --git a/z1/app/Dockerfile b/z1/app/Dockerfile new file mode 100644 index 0000000..f6bce7e --- /dev/null +++ b/z1/app/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.9-slim + +# Set the working directory +WORKDIR /app + +# Copy the requirements file and install Python dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the application source code +COPY app.py . + +# Expose port 5000 for the Flask application +EXPOSE 5000 + +# Start the Flask application +CMD ["python", "app.py"] diff --git a/z1/app/app.py b/z1/app/app.py new file mode 100644 index 0000000..661aee9 --- /dev/null +++ b/z1/app/app.py @@ -0,0 +1,149 @@ +from flask import Flask, request, render_template_string, redirect, url_for +import os +import psycopg2 + +app = Flask(__name__) + +# Retrieve database connection settings +db_host = os.environ.get("DB_HOST", "postgres_db") +db_name = os.environ.get("POSTGRES_DB", "contacts_db") +db_user = os.environ.get("POSTGRES_USER", "user") +db_password = os.environ.get("POSTGRES_PASSWORD", "password") + +# Function to make connection to database +def get_db_connection(): + conn = psycopg2.connect( + host=db_host, + database=db_name, + user=db_user, + password=db_password + ) + return conn + +# Init database & create contacts table if doesn't exist +def init_db(): + conn = get_db_connection() + cur = conn.cursor() + cur.execute(""" + CREATE TABLE IF NOT EXISTS contacts ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + phone VARCHAR(20) NOT NULL + ); + """) + conn.commit() + cur.close() + conn.close() + +@app.route("/", methods=["GET", "POST"]) +def index(): + if request.method == "POST": + name = request.form["name"] + email = request.form["email"] + phone = request.form["phone"] + + # Add new contact at the database + conn = get_db_connection() + cur = conn.cursor() + cur.execute("INSERT INTO contacts (name, email, phone) VALUES (%s, %s, %s)", + (name, email, phone)) + conn.commit() + cur.close() + conn.close() + + # Show all contacts + conn = get_db_connection() + cur = conn.cursor() + cur.execute("SELECT * FROM contacts") + contacts = cur.fetchall() + cur.close() + conn.close() + + return render_template_string(""" + +