From 0ea108cec691efddcd0dbb59a7f61b501d8abe83 Mon Sep 17 00:00:00 2001 From: Yuefii Date: Sat, 24 Aug 2024 12:16:29 +0700 Subject: [PATCH] chore: adding api(get) districts --- app/__init__.py | 3 ++- app/models.py | 9 +++++++++ app/routes.py | 17 ++++++++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3960f4a..95dba39 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,9 +15,10 @@ def home(): return render_template("index.html") with app.app_context(): - from app.routes import province_bp, regency_bp + from app.routes import province_bp, regency_bp, district_bp app.register_blueprint(province_bp) app.register_blueprint(regency_bp) + app.register_blueprint(district_bp) db.create_all() return app diff --git a/app/models.py b/app/models.py index bea0ab3..d2315c4 100644 --- a/app/models.py +++ b/app/models.py @@ -30,3 +30,12 @@ class Regencies(db.Model): ) name = db.Column(db.String(255), nullable=False) province = db.relationship("Provinces", backref=db.backref("regencies", lazy=True)) + + +class Districts(db.Model): + code = db.Column(db.String(8), primary_key=True) + regency_code = db.Column( + db.String(5), db.ForeignKey("regencies.code"), nullable=False + ) + name = db.Column(db.String(255), nullable=False) + regency = db.relationship("Regencies", backref=db.backref("districts", lazy=True)) diff --git a/app/routes.py b/app/routes.py index e23df3a..8f17f1c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,8 +1,9 @@ from flask import Blueprint, jsonify, request -from app.models import Provinces, Regencies +from app.models import Districts, Provinces, Regencies province_bp = Blueprint("provinces", __name__) regency_bp = Blueprint("regencies", __name__) +district_bp = Blueprint("districts", __name__) @province_bp.route("/api/provinces", methods=["GET"]) @@ -24,3 +25,17 @@ def get_regencies(): return jsonify({"message": "no regencies found for given province code"}), 404 response = [{"code": regency.code, "name": regency.name} for regency in regencies] return jsonify({"data": response}) + + +@district_bp.route("/api/districts", methods=["GET"]) +def get_districts(): + regency_code = request.args.get("regency_code") + if not regency_code: + return jsonify({"error": "regency code is required"}), 400 + districts = Districts.query.filter_by(regency_code=regency_code).all() + if not districts: + return jsonify({"message": "no districts found for given regency code"}) + response = [ + {"code": district.code, "name": district.name} for district in districts + ] + return jsonify({"data": response})