Enhance set_record function to check current value before updating and improve response messages for clarity
This commit is contained in:
17
app.py
17
app.py
@@ -5,6 +5,7 @@ from flask_httpauth import HTTPBasicAuth
|
||||
from base64 import b64encode
|
||||
from requests import get, put, delete
|
||||
from os import getenv
|
||||
import jmespath
|
||||
|
||||
# Define global variables for MIAB host and auth header, to be set during authentication
|
||||
MIAB_HOST = getenv('MIAB_HOST', 'localhost')
|
||||
@@ -37,6 +38,16 @@ def set_record(qname, rtype, value = None):
|
||||
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:
|
||||
return f'OK, no change' # No change needed
|
||||
|
||||
# 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
|
||||
@@ -47,10 +58,10 @@ def set_record(qname, rtype, value = None):
|
||||
status = 502
|
||||
else:
|
||||
status = 500
|
||||
return Response(f'ERROR\n', status=status)
|
||||
return Response(f'ERROR: {resp.status_code}\n', status=status)
|
||||
|
||||
# Success
|
||||
return f'OK\n'
|
||||
return f'OK, record set'
|
||||
|
||||
@app.route('/api/deleterecord/<qname>/<rtype>', methods=['GET', 'DELETE'])
|
||||
@auth.login_required
|
||||
@@ -70,7 +81,7 @@ def delete_record(qname, rtype):
|
||||
return Response(f'ERROR\n', status=status)
|
||||
|
||||
# Success
|
||||
return f'OK\n'
|
||||
return f'OK, record deleted.\n'
|
||||
|
||||
@app.route('/api/listrecords', methods=['GET'], defaults={'qname': None, 'rtype': None})
|
||||
@app.route('/api/listrecords/<qname>', methods=['GET'], defaults={'rtype': None})
|
||||
|
||||
Reference in New Issue
Block a user