forked from devfile-samples/devfile-sample-python-basic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
65 lines (53 loc) · 1.58 KB
/
app.py
File metadata and controls
65 lines (53 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from flask import Flask, request, jsonify
import mysql.connector
app = Flask(__name__)
def get_db():
return mysql.connector.connect(
host="mysql",
user="f832139",
password="password",
database="sampledb"
)
# INSERT
@app.route("/insert", methods=["POST"])
def insert_row():
data = request.json
name = data.get("name")
role = data.get("role")
conn = get_db()
cursor = conn.cursor()
cursor.execute("INSERT INTO employees (name, role) VALUES (%s, %s)", (name, role))
conn.commit()
return jsonify({"message": "Row inserted", "id": cursor.lastrowid})
# UPDATE
@app.route("/update/<int:emp_id>", methods=["PUT"])
def update_row(emp_id):
data = request.json
name = data.get("name")
role = data.get("role")
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"UPDATE employees SET name=%s, role=%s WHERE id=%s",
(name, role, emp_id)
)
conn.commit()
return jsonify({"message": "Row updated"})
# DELETE
@app.route("/delete/<int:emp_id>", methods=["DELETE"])
def delete_row(emp_id):
conn = get_db()
cursor = conn.cursor()
cursor.execute("DELETE FROM employees WHERE id=%s", (emp_id,))
conn.commit()
return jsonify({"message": "Row deleted"})
# OPTIONAL: fetch all rows
@app.route("/employees", methods=["GET"])
def get_all():
conn = get_db()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
return jsonify(rows)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8081, debug=True)