|
1 | | -from flask import Flask, request, jsonify |
2 | | -import mysql.connector |
| 1 | +from flask import Flask |
| 2 | +import os |
3 | 3 |
|
4 | 4 | app = Flask(__name__) |
5 | 5 |
|
6 | | -def get_db(): |
7 | | - return mysql.connector.connect( |
8 | | - host="localhost", |
9 | | - user="f832139", |
10 | | - password="password", |
11 | | - database="sampledb" |
12 | | - ) |
| 6 | +@app.route('/') |
| 7 | +def hello(): |
| 8 | + return "Hello World!" |
13 | 9 |
|
14 | | -# INSERT |
15 | | -@app.route("/insert", methods=["POST"]) |
16 | | -def insert_row(): |
17 | | - data = request.json |
18 | | - name = data.get("name") |
19 | | - role = data.get("role") |
| 10 | +if __name__ == '__main__': |
| 11 | + port = os.environ.get('FLASK_PORT') or 8080 |
| 12 | + port = int(port) |
20 | 13 |
|
21 | | - conn = get_db() |
22 | | - cursor = conn.cursor() |
23 | | - cursor.execute("INSERT INTO employees (name, role) VALUES (%s, %s)", (name, role)) |
24 | | - conn.commit() |
25 | | - |
26 | | - return jsonify({"message": "Row inserted", "id": cursor.lastrowid}) |
27 | | - |
28 | | -# UPDATE |
29 | | -@app.route("/update/<int:emp_id>", methods=["PUT"]) |
30 | | -def update_row(emp_id): |
31 | | - data = request.json |
32 | | - name = data.get("name") |
33 | | - role = data.get("role") |
34 | | - |
35 | | - conn = get_db() |
36 | | - cursor = conn.cursor() |
37 | | - cursor.execute( |
38 | | - "UPDATE employees SET name=%s, role=%s WHERE id=%s", |
39 | | - (name, role, emp_id) |
40 | | - ) |
41 | | - conn.commit() |
42 | | - |
43 | | - return jsonify({"message": "Row updated"}) |
44 | | - |
45 | | -# DELETE |
46 | | -@app.route("/delete/<int:emp_id>", methods=["DELETE"]) |
47 | | -def delete_row(emp_id): |
48 | | - conn = get_db() |
49 | | - cursor = conn.cursor() |
50 | | - cursor.execute("DELETE FROM employees WHERE id=%s", (emp_id,)) |
51 | | - conn.commit() |
52 | | - |
53 | | - return jsonify({"message": "Row deleted"}) |
54 | | - |
55 | | -# OPTIONAL: fetch all rows |
56 | | -@app.route("/employees", methods=["GET"]) |
57 | | -def get_all(): |
58 | | - conn = get_db() |
59 | | - cursor = conn.cursor(dictionary=True) |
60 | | - cursor.execute("SELECT * FROM employees") |
61 | | - rows = cursor.fetchall() |
62 | | - return jsonify(rows) |
63 | | - |
64 | | -if __name__ == "__main__": |
65 | | - app.run(debug=True) |
| 14 | + app.run(port=port,host='0.0.0.0') |
0 commit comments