Skip to content

Commit

Permalink
chore: adding api(get) districts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuefii committed Aug 24, 2024
1 parent 38dd18c commit 0ea108c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
3 changes: 2 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
17 changes: 16 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -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"])
Expand All @@ -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})

0 comments on commit 0ea108c

Please sign in to comment.