from flask import Flask, request, jsonify import os import psycopg2 import time app = Flask(__name__) # Database Configuration db_host = os.environ.get("DB_HOST", "blog-db-service") db_name = os.environ.get("POSTGRES_DB", "blogdb") db_user = os.environ.get("POSTGRES_USER", "admin") 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(): max_retries = 10 retry_delay = 5 # seconds for attempt in range(max_retries): try: print(f"Attempt {attempt+1}/{max_retries} to connect to database...") 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() print("Table 'articles' created successfully") return True except Exception as e: print(f"Database connection attempt {attempt+1}/{max_retries} failed: {e}") if attempt < max_retries - 1: print(f"Retrying in {retry_delay} seconds...") time.sleep(retry_delay) print("Failed to create table after multiple attempts") return False # Initialize the variable at startup table_created = False @app.route("/", methods=["GET", "POST"]) def index(): global table_created # If the table is not yet created, try to create it if not table_created: table_created = create_table() # Check if the table has been created before continuing if not table_created: return "Database connection failed. Please try again later.", 500 try: 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"""
{a[2]}