From 9051fa1c2b7afdbe6f3370022e87b5cf0e2a807a Mon Sep 17 00:00:00 2001 From: Coline Reberga Date: Sun, 16 Mar 2025 10:21:05 +0000 Subject: [PATCH] Add folders --- app/Dockerfile | 18 ++++++++ app/app.py | 100 +++++++++++++++++++++++++++++++++++++++++++ app/requirements.txt | 3 ++ 3 files changed, 121 insertions(+) create mode 100644 app/Dockerfile create mode 100644 app/app.py create mode 100644 app/requirements.txt diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..af7bcac --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,18 @@ +# Basic image from Docker Hub +FROM python:3.9-slim + +# Container working directory settings +WORKDIR /app + +# Copy the requirements file and install Python +COPY requirements.txt . +RUN pip install -r requirements.txt + +# Copy application files to the image +COPY app.py . + +# Expose port 5000 for the Flask application +EXPOSE 5000 + +# Program to run +CMD ["python", "app.py"] diff --git a/app/app.py b/app/app.py new file mode 100644 index 0000000..448b414 --- /dev/null +++ b/app/app.py @@ -0,0 +1,100 @@ +from flask import Flask, request, jsonify +import os +import psycopg2 + +app = Flask(__name__) + +# Database Configuration +db_host = os.environ.get("DB_HOST", "postgres_db") +db_name = os.environ.get("POSTGRES_DB", "sampledb") +db_user = os.environ.get("POSTGRES_USER", "user") +db_password = os.environ.get("POSTGRES_PASSWORD", "password") + +def get_db_connection(): + return psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_password) + +def create_table(): + conn = get_db_connection() + cur = conn.cursor() + cur.execute(''' + CREATE TABLE IF NOT EXISTS articles ( + id SERIAL PRIMARY KEY, + title TEXT NOT NULL, + content TEXT NOT NULL + ) + ''') + conn.commit() + cur.close() + conn.close() + +@app.route("/", methods=["GET", "POST"]) +def index(): + conn = get_db_connection() + cur = conn.cursor() + + if request.method == "POST": + title = request.form.get("title") + content = request.form.get("content") + if title and content: + cur.execute("INSERT INTO articles (title, content) VALUES (%s, %s)", (title, content)) + conn.commit() + + cur.execute("SELECT * FROM articles ORDER BY id DESC") + articles = cur.fetchall() + cur.close() + conn.close() + + return f""" + + + My Blog + + + +
+
+

My Blog

+
+ + + +
+
+
+

Articles

+ {''.join(f'

{a[1]}

{a[2]}

' for a in articles)} +
+
+ + + """ + +@app.route("/delete/", methods=["POST"]) +def delete_article(article_id): + conn = get_db_connection() + cur = conn.cursor() + cur.execute("DELETE FROM articles WHERE id = %s", (article_id,)) + conn.commit() + cur.close() + conn.close() + return "" + +if __name__ == "__main__": + create_table() + app.run(host="0.0.0.0", port=5000) \ No newline at end of file diff --git a/app/requirements.txt b/app/requirements.txt new file mode 100644 index 0000000..13f66f1 --- /dev/null +++ b/app/requirements.txt @@ -0,0 +1,3 @@ +Flask +psycopg2-binary +requests