From 80492d466c7c823e5bf58c3d66ba84cdfee0ab4b Mon Sep 17 00:00:00 2001 From: Dita Aji Pratama Date: Sat, 7 Jun 2025 15:18:24 +0700 Subject: [PATCH] Pertemuan ke 10: CRUD API Selesai --- handler.py | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/handler.py b/handler.py index 0e1cb37..7e54be6 100644 --- a/handler.py +++ b/handler.py @@ -6,8 +6,9 @@ # You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/. from bottle import Bottle, route, request, response -from config import directory +from config import directory, database +import mysql.connector as mariadb import json import templates.plain.main as template_public @@ -37,36 +38,51 @@ def list(crud): "endpoint":f"/api/{crud}", "data":[] } + + db_main = mariadb.connect(**database.db_main) + cursor = db_main.cursor(dictionary=True) if crud == "create": + name = params["name" ] + phone = params["phone" ] + cursor.execute("INSERT INTO `member` VALUES (DEFAULT, %s, %s) ;" , (name, phone) ) keluaran["status"] = "Berhasil" - keluaran["message"] = "Dummy: Selamat data anda telah ditambah" + keluaran["message"] = "Selamat data anda telah ditambah" keluaran["data"] = { - "food":params["food"] + "name":name, + "phone":phone } elif crud == "read": + cursor.execute("SELECT * FROM `member`; ") + member_list = cursor.fetchall() keluaran["status"] = "Berhasil" - keluaran["message"] = "Dummy: Data collected" - keluaran["data"] = [ - "Banana", - "Apple", - "Marshmallow" - ] + keluaran["message"] = "Data collected" + keluaran["data"] = member_list elif crud == "update": + key = params["key" ] + name = params["name" ] + phone = params["phone" ] + cursor.execute("UPDATE `member` SET `name` = %s, `phone` = %s WHERE `id` = %s ;" , (name, phone, key) ) keluaran["status"] = "Berhasil" - keluaran["message"] = "Dummy: Belum dibikin" + keluaran["message"] = "Belum dibikin" keluaran["data"] = { - "old":params["key"], - "new":params["change"] + "key":params["key"], + "name":params["name"], + "phone":params["phone"] } elif crud == "delete": + key = params["key" ] + cursor.execute("DELETE FROM `member` WHERE `id` = %s ;" , (key,) ) keluaran["status"] = "Berhasil" - keluaran["message"] = "Dummy: Belum dibikin" + keluaran["message"] = "Data sudah terhapus selamanya!" else: pass + cursor.close() + db_main.close() + return json.dumps(keluaran, indent = 2).encode()