Удалить app.py
This commit is contained in:
parent
29fd3fd99e
commit
979b1403e0
58
app.py
58
app.py
@ -1,58 +0,0 @@
|
||||
from flask import Flask, render_template, request, jsonify
|
||||
import psycopg2
|
||||
import os
|
||||
|
||||
app = Flask(__name__, template_folder="templates", static_folder="static")
|
||||
|
||||
# Подключение к БД
|
||||
def get_db_connection():
|
||||
conn = psycopg2.connect(
|
||||
host="db",
|
||||
database="mydatabase",
|
||||
user="postgres",
|
||||
password=os.getenv("POSTGRES_PASSWORD", "mysecretpassword")
|
||||
)
|
||||
return conn
|
||||
|
||||
# Главная страница с HTML
|
||||
@app.route("/")
|
||||
def home():
|
||||
conn = get_db_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id, name FROM users;")
|
||||
users = cur.fetchall()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return render_template("index.html", users=users)
|
||||
|
||||
# API для добавления пользователя
|
||||
@app.route("/add_user", methods=["POST"])
|
||||
def add_user():
|
||||
name = request.form.get("name")
|
||||
if name:
|
||||
conn = get_db_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute("INSERT INTO users (name) VALUES (%s) RETURNING id;", (name,))
|
||||
user_id = cur.fetchone()[0]
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return jsonify({"id": user_id, "name": name}), 201
|
||||
return jsonify({"error": "Имя не может быть пустым"}), 400
|
||||
|
||||
# API для удаления пользователя
|
||||
@app.route("/delete_user/<int:user_id>", methods=["POST"])
|
||||
def delete_user(user_id):
|
||||
conn = get_db_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM users WHERE id = %s RETURNING id;", (user_id,))
|
||||
deleted = cur.fetchone()
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
if deleted:
|
||||
return jsonify({"message": "Пользователь удален"})
|
||||
return jsonify({"error": "Пользователь не найден"}), 404
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
Loading…
Reference in New Issue
Block a user