Team Ai
Apppublic

GamerC0der/postgres

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
app.py98 linesDownload Raw Back to root
1from flask import Flask, request, jsonify, render_template_string2import psycopg23import os4 5app = Flask(__name__)6 7DB_PARAMS = {8    'dbname': os.getenv('POSTGRES_DB', 'mydatabase'),9    'user': os.getenv('POSTGRES_USER', 'myuser'),10    'password': os.getenv('POSTGRES_PASSWORD', 'mypassword'),11    'host': 'localhost',12    'port': 543213}14 15def get_conn():16    return psycopg2.connect(**DB_PARAMS)17 18@app.route("/")19def index():20    html = """21    <html>22    <head>23      <title>Database Status</title>24      <style>25        body { background-color: #121212; color: #eeeeee; font-family: sans-serif; padding: 2em; }26        textarea, input, button { background-color: #222; color: #eee; border: 1px solid #555; padding: 5px; }27        button { cursor: pointer; }28      </style>29    </head>30    <body>31      <h1>Database Status</h1>32      <div id="status">Loading...</div>33 34      <h2>Run Query</h2>35      <textarea id="query" rows="4" cols="60">SELECT * FROM pg_tables LIMIT 5;</textarea><br>36      <button onclick="runQuery()">Execute</button>37 38      <h3>Results</h3>39      <pre id="results"></pre>40 41      <script>42        async function loadStatus() {43          const res = await fetch('/api/health');44          const data = await res.json();45          document.getElementById('status').textContent =46            'Health: ' + data.status + ' | ' +47            'Connected: ' + data.connected;48        }49        async function runQuery() {50          const sql = document.getElementById('query').value;51          const res = await fetch('/api/query', {52            method: 'POST',53            headers: { 'Content-Type': 'application/json' },54            body: JSON.stringify({ query: sql })55          });56          const data = await res.json();57          document.getElementById('results').textContent =58            JSON.stringify(data, null, 2);59        }60        loadStatus();61      </script>62    </body>63    </html>64    """65    return render_template_string(html)66 67@app.route("/api/health")68def health():69    try:70        conn = get_conn()71        conn.close()72        return jsonify({'status': 'ok', 'connected': True})73    except Exception as e:74        return jsonify({'status': 'error', 'connected': False, 'detail': str(e)}), 50075 76@app.route("/api/query", methods=["POST"])77def query():78    data = request.get_json()79    sql = data.get("query", "")80    try:81        conn = get_conn()82        cur = conn.cursor()83        cur.execute(sql)84        if cur.description:85            rows = cur.fetchall()86            columns = [desc[0] for desc in cur.description]87            result = [dict(zip(columns, row)) for row in rows]88        else:89            conn.commit()90            result = {"rows_affected": cur.rowcount}91        cur.close()92        conn.close()93        return jsonify(result)94    except Exception as e:95        return jsonify({"error": str(e)}), 40096 97if __name__ == "__main__":98    app.run(host="0.0.0.0", port=7860)