|
import os |
|
from flask import Flask, request, jsonify |
|
from psycopg2 import connect, sql |
|
import psycopg2.extras |
|
import gradio as gr |
|
import threading |
|
|
|
|
|
DB_NAME = os.getenv("DB_NAME") |
|
DB_USER = os.getenv("DB_USER") |
|
DB_PASSWORD = os.getenv("DB_PASSWORD") |
|
DB_HOST = os.getenv("DB_HOST") |
|
DB_PORT = os.getenv("DB_PORT") |
|
APP_PASSWORD = os.getenv("APP_PASSWORD") |
|
|
|
|
|
def get_db_connection(): |
|
return connect( |
|
dbname=DB_NAME, |
|
user=DB_USER, |
|
password=DB_PASSWORD, |
|
host=DB_HOST, |
|
port=DB_PORT |
|
) |
|
|
|
|
|
app = Flask(__name__) |
|
|
|
|
|
@app.route("/run_sql", methods=["POST"]) |
|
def run_sql(): |
|
|
|
password = request.json.get("password") |
|
command = request.json.get("command") |
|
|
|
|
|
if password != APP_PASSWORD: |
|
return jsonify({"error": "Invalid password!"}), 401 |
|
|
|
|
|
if not command: |
|
return jsonify({"error": "No SQL command provided!"}), 400 |
|
|
|
|
|
conn = None |
|
result = None |
|
try: |
|
|
|
conn = get_db_connection() |
|
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) |
|
|
|
|
|
cursor.execute(command) |
|
if command.strip().lower().startswith("select"): |
|
result = cursor.fetchall() |
|
else: |
|
conn.commit() |
|
result = {"message": "Command executed successfully!"} |
|
except Exception as e: |
|
result = {"error": f"Error executing command: {str(e)}"} |
|
finally: |
|
if conn: |
|
conn.close() |
|
|
|
return jsonify(result) |
|
|
|
|
|
def gradio_interface(): |
|
def greet(name): |
|
return f"Hello {name}!" |
|
|
|
interface = gr.Interface(fn=greet, inputs="text", outputs="text") |
|
interface.launch(share=True, inline=True) |
|
|
|
|
|
def run_flask(): |
|
app.run(host="0.0.0.0", port=5050) |
|
|
|
|
|
if __name__ == "__main__": |
|
flask_thread = threading.Thread(target=run_flask) |
|
flask_thread.daemon = True |
|
flask_thread.start() |
|
|
|
|
|
gradio_interface() |
|
|