Refactor set_record and delete_record functions to improve value checking and response handling

This commit is contained in:
2025-12-28 13:02:58 +01:00
parent dbf59fd124
commit 59f3d2377d

16
app.py
View File

@@ -22,7 +22,7 @@ def verify(username, password):
result = get(f'https://{MIAB_HOST}/admin/dns/custom/test/A', headers={'Authorization': MIAB_AUTH_HEADER})
if result.status_code != 200:
return False
return True
@app.route('/api/setrecord/<qname>/<value>', methods=['GET'], defaults={'rtype': 'A'})
@@ -36,12 +36,12 @@ def set_record(qname, rtype, value = None):
# Use request data as value for PUT method
if request.method == 'PUT':
value = request.data.decode()
url = f'https://{MIAB_HOST}/admin/dns/custom/{qname}/{rtype}'
# Check the currect value
resp = get(url, headers={'Authorization': MIAB_AUTH_HEADER})
if resp.status_code == 200:
current_value = jmespath.compile('[0].value').search(resp.json())
if current_value == value:
@@ -49,7 +49,7 @@ def set_record(qname, rtype, value = None):
# Values are different or record does not exist, proceed to set the new value
resp = put(url, headers={'Authorization': MIAB_AUTH_HEADER, 'Content-Type': 'text/plain'}, data=value)
# Propagate 400-499 as is, 500+ as 502
if resp.status_code != 200:
if 400 <= resp.status_code < 500:
@@ -59,7 +59,7 @@ def set_record(qname, rtype, value = None):
else:
status = 500
return Response(f'ERROR: {resp.status_code}\n', status=status)
# Success
return f'OK, record set'
@@ -69,7 +69,7 @@ def delete_record(qname, rtype):
global MIAB_HOST, MIAB_AUTH_HEADER
url = f'https://{MIAB_HOST}/admin/dns/custom/{qname}/{rtype}'
resp = delete(url, headers={'Authorization': MIAB_AUTH_HEADER, 'Content-Type': 'text/plain'}, data='')
# Propagate 400-499 as is, 500+ as 502
if resp.status_code != 200:
if 400 <= resp.status_code < 500:
@@ -79,7 +79,7 @@ def delete_record(qname, rtype):
else:
status = 500
return Response(f'ERROR\n', status=status)
# Success
return f'OK, record deleted.\n'
@@ -98,4 +98,4 @@ def list_records(qname, rtype):
return jsonify(resp.json())
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
app.run(host='0.0.0.0', port=8080)