diff --git a/api/README.md b/api/README.md index 9b14664..b3a7223 100644 --- a/api/README.md +++ b/api/README.md @@ -1,105 +1,84 @@ -## Instalasi dan Penggunaan Web API -### Instalasi -1. Install python -2. Buka CMD atau Command-prompt -3. cd nama/folder/costapy (di copy) -4. Jalankan command ini di CMD: - ```sh - py -m pip install --upgrade pip - py -m pip install bottle - py -m pip install beaker - py -m pip install mako - py -m pip install mysql-connector - py -m pip install bcrypt - py -m pip install pyjwt[crypto] - ``` -5. Buka folder project pake VSCode -6. Buka file di config/server.py -7. servernya ganti dari 'gunicorn' ke 'wsgiref' (di save) -### Penggunaan -8. Buka CMD lalu jalanin service-nya: - - Untuk Windows: - ```dos - cd C:\direktori\folder\kamu - py costa.py - ``` - - Untuk Linux/MacOS: - ```sh - cd directory/folder/kamu - python costapy - ``` -9. kalau keluar output http://localhost:11000 artinya berhasil -10. Install bruno -11. bikin collection -12. test localhost:11000 -13. Praktek ke VSCode +# CostaPy +a Python WSGI Web Framework. Build with Bottle and Mako. -## Instalasi dan Implementasi MariaDB +## License -### Instalasi +CostaPy -- Windows: Download dari mariadb.org atau dari xampp lalu install -- Mac: Install melalui brew -- Debian/Ubuntu: sudo apt install mariadb-server -- Alternative lain: Pakai container (Docker) +Copyright (C) 2022 Dita Aji Pratama -### Penggunaan +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. -- Terminal (Linux/MacOS): mariadb -u root -p -- MySQL Client Command Prompt: Buka MySQL client lalu masukan password +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. -### Implementasi (Buat Table di dalam MySQL Client) +You should have received a copy of the GNU General Public License +along with this program. If not, see https://www.gnu.org/licenses/. -1. CREATE DATABASE latihan; -2. USE latihan; -3. CREATE TABLE member ( - id int(11) not null auto_increment primary key, - name varchar(36) not null, - phone varchar(14) null - ); -4. SHOW COLUMNS FROM member; -5. INSERT INTO member VALUES ( - DEFAULT, - 'Nama_Kalian', - 'Telp_Kalian' - ); -6. SELECT * FROM member; -7. exit +# Getting Starter -## Persiapan bagi yang ketinggalan sebelum jalanin Widuri Client -- Download Python [disini](https://www.python.org/downloads/) lalu install -- Selesaikan task Instalasi dan Implementasi MariaDB dulu -- Clone atau Download Widuri Client [disini](https://gitea.ditaajipratama.net/istek-widuri/widuri-client) -- Clone atau Download Widuri API [disini](https://gitea.ditaajipratama.net/istek-widuri/widuri-api) -- Buka CMD (Command-Prompt) lalu install kebutuhan library dengan command berikut: - - Untuk Linux/MacOS: - ```sh - cd directory/folder/widuri-api - python -m pip install --upgrade pip - python -m pip install bottle - python -m pip install beaker - python -m pip install mako - python -m pip install mysql-connector - python -m pip install bcrypt - python -m pip install pyjwt[crypto] - ``` - - Untuk Windows: - ```dos - cd C:\direktori\folder\widuri-api - py -m pip install --upgrade pip - py -m pip install bottle - py -m pip install beaker - py -m pip install mako - py -m pip install mysql-connector - py -m pip install bcrypt - py -m pip install pyjwt[crypto] - ``` +## Requirement + +You need a `git`, `python`, `pip`, and `venv` before using CostaPy. + +Install them using the following commands on your `Debian` or `Ubuntu` system. + +```bash +sudo apt update +sudo apt install git python3 python3-venv python3-pip +``` + +or you can use the following command to install similar packages using `brew`, the package manager for `macOS`: + +```bash +brew install git python3 +``` +Installs Python 3 with `brew`, which includes `python3`, `pip3`, and the `venv` module. If you don't have Homebrew installed on your `macOS`, you can install it first. + +or go to the [git downloads page](https://git-scm.com/downloads) and a [Python downloads page](https://www.python.org/downloads/) and download the latest version of git Python for `Windows`. + +## Installation + +Download from repository +```bash +git clone https://gitea.ditaajipratama.net/aji/costapy.git +``` + +Go to the directory and install with this command: + +```bash +cd costapy +bash install.sh +``` + +Use `cat install.sh` if you want to see a completed command. + +## Usage + +Use this command below to start the web service and it will run on port `11000` by default +```bash +.venv/bin/python3 costa.py costapy-welcome +``` +Here, `costapy-welcome` is the label of your service. You can replace it with any name you prefer. + +## Trivia + +- Why must `venv`? + + `venv` is a module in Python that provides support for creating lightweight, isolated Python environments, known as virtual environments. Each virtual environment has its own installation directories and can have its own versions of Python packages, independent of the system-wide Python environment. + + When deploying a Python application, using a virtual environment ensures that only the required packages (and their specific versions) are bundled. This reduces the risk of deploying unnecessary packages or incompatible versions that could lead to runtime errors. + + Using `venv` is a widely accepted best practice in the Python community. It encourages good habits in dependency management, ensuring that projects are self-contained and reducing the potential for "dependency hell." + + When a project is no longer needed, deleting its virtual environment is straightforward and does not affect other projects or the system's Python environment. + +- Why I add `venv` on my `gitignore`? + + Committing `venv` to Git is gross. Virtual environments can contain thousands of files and their size can be in gigabytes. Committing them to Git can overload and clutter your source code repo with unnecessary files and cause confusion for anyone trying to clone and run the source code on their machine. -## Pengunaan widuri-client -1. Buka Command-Prompt -2. Ke directory Widuri API (Contoh: `cd C:\direktori\widuri-api`) -3. Nyalain service Widuri API: `py costa.py` -4. Buka Command-Prompt baru -5. Ke directory Widuri Client (Contoh: `cd C:\direktori\widuri-client`) -6. Nyalain service Widuri Client: `py -m http.server 12000` -7. buka `localhost:12000` di Browser diff --git a/api/README.md.bak b/api/README.md.bak deleted file mode 100644 index b3a7223..0000000 --- a/api/README.md.bak +++ /dev/null @@ -1,84 +0,0 @@ -# CostaPy -a Python WSGI Web Framework. Build with Bottle and Mako. - -## License - -CostaPy - -Copyright (C) 2022 Dita Aji Pratama - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see https://www.gnu.org/licenses/. - -# Getting Starter - -## Requirement - -You need a `git`, `python`, `pip`, and `venv` before using CostaPy. - -Install them using the following commands on your `Debian` or `Ubuntu` system. - -```bash -sudo apt update -sudo apt install git python3 python3-venv python3-pip -``` - -or you can use the following command to install similar packages using `brew`, the package manager for `macOS`: - -```bash -brew install git python3 -``` -Installs Python 3 with `brew`, which includes `python3`, `pip3`, and the `venv` module. If you don't have Homebrew installed on your `macOS`, you can install it first. - -or go to the [git downloads page](https://git-scm.com/downloads) and a [Python downloads page](https://www.python.org/downloads/) and download the latest version of git Python for `Windows`. - -## Installation - -Download from repository -```bash -git clone https://gitea.ditaajipratama.net/aji/costapy.git -``` - -Go to the directory and install with this command: - -```bash -cd costapy -bash install.sh -``` - -Use `cat install.sh` if you want to see a completed command. - -## Usage - -Use this command below to start the web service and it will run on port `11000` by default -```bash -.venv/bin/python3 costa.py costapy-welcome -``` -Here, `costapy-welcome` is the label of your service. You can replace it with any name you prefer. - -## Trivia - -- Why must `venv`? - - `venv` is a module in Python that provides support for creating lightweight, isolated Python environments, known as virtual environments. Each virtual environment has its own installation directories and can have its own versions of Python packages, independent of the system-wide Python environment. - - When deploying a Python application, using a virtual environment ensures that only the required packages (and their specific versions) are bundled. This reduces the risk of deploying unnecessary packages or incompatible versions that could lead to runtime errors. - - Using `venv` is a widely accepted best practice in the Python community. It encourages good habits in dependency management, ensuring that projects are self-contained and reducing the potential for "dependency hell." - - When a project is no longer needed, deleting its virtual environment is straightforward and does not affect other projects or the system's Python environment. - -- Why I add `venv` on my `gitignore`? - - Committing `venv` to Git is gross. Virtual environments can contain thousands of files and their size can be in gigabytes. Committing them to Git can overload and clutter your source code repo with unnecessary files and cause confusion for anyone trying to clone and run the source code on their machine. - diff --git a/api/bruno.json b/api/bruno.json new file mode 100644 index 0000000..5d23613 --- /dev/null +++ b/api/bruno.json @@ -0,0 +1,6 @@ +{ + "version": "1", + "name": "costapy", + "type": "collection", + "ignore": ["node_modules", ".git"] +} \ No newline at end of file diff --git a/api/bruno/Create API.bru b/api/bruno/Create API.bru new file mode 100644 index 0000000..ac5f394 --- /dev/null +++ b/api/bruno/Create API.bru @@ -0,0 +1,18 @@ +meta { + name: Create API + type: http + seq: 6 +} + +post { + url: http://{{BASE_URL}}/api/create + body: json + auth: inherit +} + +body:json { + { + "name": "Test Lagi", + "phone": "080000000002" + } +} diff --git a/api/bruno/Create.bru b/api/bruno/Create.bru deleted file mode 100644 index 9b625b5..0000000 --- a/api/bruno/Create.bru +++ /dev/null @@ -1,26 +0,0 @@ -meta { - name: Create - type: http - seq: 2 -} - -get { - url: http://localhost:11000/api/:crud - body: json - auth: none -} - -params:path { - crud: create -} - -body:json { - { - "name":"Gepeng", - "phone":"7777777" - } -} - -docs { - crud = add | edit | remove | list | detail -} diff --git a/api/bruno/Delete API.bru b/api/bruno/Delete API.bru new file mode 100644 index 0000000..3a74008 --- /dev/null +++ b/api/bruno/Delete API.bru @@ -0,0 +1,17 @@ +meta { + name: Delete API + type: http + seq: 6 +} + +delete { + url: http://{{BASE_URL}}/api/delete + body: json + auth: inherit +} + +body:json { + { + "id": 8 + } +} diff --git a/api/bruno/Delete.bru b/api/bruno/Delete.bru deleted file mode 100644 index 529a0fe..0000000 --- a/api/bruno/Delete.bru +++ /dev/null @@ -1,25 +0,0 @@ -meta { - name: Delete - type: http - seq: 5 -} - -get { - url: http://localhost:11000/api/:crud - body: json - auth: none -} - -params:path { - crud: delete -} - -body:json { - { - "key":5 - } -} - -docs { - crud = add | edit | remove | list | detail -} diff --git a/api/bruno/Read API.bru b/api/bruno/Read API.bru new file mode 100644 index 0000000..e3a653b --- /dev/null +++ b/api/bruno/Read API.bru @@ -0,0 +1,11 @@ +meta { + name: Read API + type: http + seq: 5 +} + +get { + url: http://{{BASE_URL}}/api/read + body: none + auth: inherit +} diff --git a/api/bruno/Read.bru b/api/bruno/Read.bru deleted file mode 100644 index deca886..0000000 --- a/api/bruno/Read.bru +++ /dev/null @@ -1,26 +0,0 @@ -meta { - name: Read - type: http - seq: 3 -} - -get { - url: http://localhost:11000/api/:crud - body: none - auth: none -} - -params:path { - crud: read -} - -body:json { - { - "name":"Gepeng", - "phone":"7777777" - } -} - -docs { - crud = add | edit | remove | list | detail -} diff --git a/api/bruno/Update API.bru b/api/bruno/Update API.bru new file mode 100644 index 0000000..185d082 --- /dev/null +++ b/api/bruno/Update API.bru @@ -0,0 +1,19 @@ +meta { + name: Update API + type: http + seq: 6 +} + +put { + url: http://{{BASE_URL}}/api/update + body: json + auth: inherit +} + +body:json { + { + "id": 4, + "name": "Syahdan", + "phone": "082112586824" + } +} diff --git a/api/bruno/Update.bru b/api/bruno/Update.bru deleted file mode 100644 index 507e729..0000000 --- a/api/bruno/Update.bru +++ /dev/null @@ -1,27 +0,0 @@ -meta { - name: Update - type: http - seq: 4 -} - -get { - url: http://localhost:11000/api/:crud - body: json - auth: none -} - -params:path { - crud: update -} - -body:json { - { - "key":5, - "name":"Gemblong", - "phone":"5555" - } -} - -docs { - crud = add | edit | remove | list | detail -} diff --git a/api/bruno/bruno.json b/api/bruno/bruno.json deleted file mode 100644 index d64c14f..0000000 --- a/api/bruno/bruno.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": "1", - "name": "Pemrograman-Web-ISTEK-WIDURI", - "type": "collection", - "ignore": [ - "node_modules", - ".git" - ] -} \ No newline at end of file diff --git a/api/config/server.py b/api/config/server.py index dbbd507..8c191b8 100644 --- a/api/config/server.py +++ b/api/config/server.py @@ -4,7 +4,7 @@ host = "localhost" port = 11000 reloader = False debug = False -server = 'wsgiref' # default = 'wsgiref' +server = 'gunicorn' # default = 'wsgiref' session_opts = { 'session.type': 'file', diff --git a/api/environments/costapy local.bru b/api/environments/costapy local.bru new file mode 100644 index 0000000..bee9106 --- /dev/null +++ b/api/environments/costapy local.bru @@ -0,0 +1,3 @@ +vars { + BASE_URL: localhost:11000 +} diff --git a/api/handler.py b/api/handler.py index 1d3b678..745b596 100644 --- a/api/handler.py +++ b/api/handler.py @@ -5,17 +5,38 @@ # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # 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 +import json +from bottle import Bottle, route, response, request from config import directory, database -import mysql.connector as mariadb -import json - +import mysql.connector as mariadb import templates.plain.main as template_public import modules.public.home as public_home app = Bottle() +# Sample data to simulate a database +# also serves as a model reminder +data = { + "member": [ + { + "id": 1, + "name": "Syahdan", + "phone": "081234567890" + }, + { + "id": 2, + "name": "Dita", + "phone": "081234567891" + }, + { + "id": 3, + "name": "Aji", + "phone": "081234567892" + } + ] +} + @app.route('/') def index(): params = { @@ -26,65 +47,89 @@ def index(): return public_home.main().html(params) @app.route('/api/', method=['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE']) -def list(crud): - # Untuk menentukan tipe konten pada respon, yaitu: JSON +def index(crud): response.content_type = 'application/json' - # Mengambil request pada body, yaitu berformat JSON - params = request.json - # Keluaran default - keluaran = { - "status":"Gagal", - "message":"Anda tidak ada otoritas untuk menggunakan endpoint ini", - "endpoint":f"/api/{crud}", - "data":[] + result = { + "status": "error", + "message": f"API endpoint for /api/{crud} is not implemented yet." } db_main = mariadb.connect(**database.db_main) - cursor = db_main.cursor(dictionary=True) + cursor = db_main.cursor(dictionary=True) - if request.method == 'OPTIONS': - return None - elif crud == "create": - name = params["name" ] - phone = params["phone" ] - cursor.execute("INSERT INTO `member` VALUES (DEFAULT, %s, %s) ;" , (name, phone) ) - keluaran["status"] = "Berhasil" - keluaran["message"] = "Selamat data anda telah ditambah" - keluaran["data"] = { - "name":name, - "phone":phone + payload = request.json + if crud == "create": + name = payload["name"] + phone = payload["phone"] + + if not name or not phone: + result["status"] = "error" + result["message"] = "Name and phone are required." + return json.dumps(result, indent = 2).encode() + + data_id = cursor.execute("INSERT INTO `member` (name, phone) VALUES (%s, %s);", (name, phone)) + + result["status"] = "success" + result["message"] = f'{payload["name"]} is added to the list.' + + result["data"] = { + "name": name, + "phone": phone } - + elif crud == "read": - cursor.execute("SELECT * FROM `member`; ") - member_list = cursor.fetchall() - keluaran["status"] = "Berhasil" - keluaran["message"] = "Data collected" - keluaran["data"] = member_list - + cursor.execute("SELECT * FROM `member`;") + members = cursor.fetchall() + + if not members: + result["status"] = "error" + result["message"] = "No members found." + return json.dumps(result, indent = 2).encode() + + result["status"] = "success" + result["message"] = "Members collected." + result["data"] = members + 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"] = "Belum dibikin" - keluaran["data"] = { - "key":params["key"], - "name":params["name"], - "phone":params["phone"] + member_id = payload["id"] + name = payload["name"] + phone = payload["phone"] + + cursor.execute("UPDATE `member` SET `name` = %s, `phone` = %s WHERE `id` = %s ;" , (name, phone, member_id) ) + db_main.commit() + cursor.execute("SELECT * FROM `member` WHERE `id` = %s;", (member_id,)) + member = cursor.fetchone() + + if not member: + result["status"] = "error" + result["message"] = f'Member with ID {member_id} not found.' + return json.dumps(result, indent = 2).encode() + + result["status"] = "success" + result["message"] = f'Member with ID {member_id} is updated.' + result["data"] = { + "id" : member["id"], + "name" : member["name"], + "phone": member["phone"] } - + elif crud == "delete": - key = params["key" ] - cursor.execute("DELETE FROM `member` WHERE `id` = %s ;" , (key,) ) - keluaran["status"] = "Berhasil" - keluaran["message"] = "Data sudah terhapus selamanya!" - - else: - pass + member_id = payload["id"] + cursor.execute("SELECT * FROM `member` WHERE `id` = %s;", (member_id,)) + member = cursor.fetchone() + if not member: + result["status"] = "error" + result["message"] = f'Member with ID {member_id} not found.' + return json.dumps(result, indent = 2).encode() + + cursor.execute("DELETE FROM `member` WHERE `id` = %s;", (member_id,)) - cursor.close() - db_main.close() - - return json.dumps(keluaran, indent = 2).encode() + result["status"] = "success" + result["message"] = f'Member with ID {member_id} is deleted.' + result["data"] = { + "id" : member["id"], + "name" : member["name"], + "phone": member["phone"] + } + + return json.dumps(result, indent = 2).encode() \ No newline at end of file diff --git a/api/sql/init.sql b/api/sql/init.sql new file mode 100644 index 0000000..2898eed --- /dev/null +++ b/api/sql/init.sql @@ -0,0 +1,11 @@ +CREATE TABLE member ( + id int(11) not null auto_increment primary key, + name varchar(36) not null, + phone varchar(14) null + ); + +INSERT INTO member VALUES + (DEFAULT, 'Syahdan', '081111111111'), + (DEFAULT, 'Hafiz', '082222222222'), + (DEFAULT, 'Ashari', '083333333333'); + \ No newline at end of file