Last active
February 20, 2025 19:44
-
-
Save fl64/67261497420f64fb3c377efe698c0921 to your computer and use it in GitHub Desktop.
d8conf-app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify | |
from flask_cors import CORS | |
import psycopg2 | |
import os | |
app = Flask(__name__) | |
CORS(app, resources={r"/api/*": {"origins": "https://demo.pt.dvp.flant.dev"}}) | |
# Настройки подключения к PostgreSQL | |
DB_HOST = os.getenv('DB_HOST', 'db.demo-db.svc.cluster.local') | |
DB_USER = os.getenv('DB_USER', 'myuser') | |
DB_PASSWORD = os.getenv('DB_PASSWORD', 'mypassword') | |
DB_NAME = os.getenv('DB_NAME', 'mydb') | |
def get_db_connection(): | |
return psycopg2.connect( | |
host=DB_HOST, | |
user=DB_USER, | |
password=DB_PASSWORD, | |
dbname=DB_NAME | |
) | |
@app.route('/data', methods=['GET']) | |
def get_data(): | |
try: | |
conn = get_db_connection() | |
cur = conn.cursor() | |
cur.execute("SELECT id, name FROM test_table") | |
rows = cur.fetchall() | |
cur.close() | |
conn.close() | |
return jsonify([{"id": row[0], "name": row[1]} for row in rows]) | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
@app.route('/data', methods=['POST']) | |
def add_data(): | |
try: | |
data = request.json | |
name = data.get('name') | |
if not name: | |
return jsonify({"error": "Name is required"}), 400 | |
conn = get_db_connection() | |
cur = conn.cursor() | |
cur.execute("INSERT INTO test_table (name) VALUES (%s) RETURNING id", (name,)) | |
new_id = cur.fetchone()[0] | |
conn.commit() | |
cur.close() | |
conn.close() | |
return jsonify({"id": new_id, "name": name}), 201 | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
@app.route('/data/<int:id>', methods=['DELETE']) | |
def delete_data(id): | |
try: | |
conn = get_db_connection() | |
cur = conn.cursor() | |
cur.execute("DELETE FROM test_table WHERE id = %s", (id,)) | |
conn.commit() | |
cur.close() | |
conn.close() | |
return jsonify({"message": f"Record with ID {id} deleted"}) | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment