]> git.ipfire.org Git - ddns.git/commitdiff
system: Add native support for JSON requests and responses
authorMichael Tremer <michael.tremer@ipfire.org>
Fri, 29 Aug 2025 22:05:46 +0000 (22:05 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Fri, 29 Aug 2025 22:05:46 +0000 (22:05 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/ddns/system.py

index 48c9a8f88fdde2b922cb6548e450c9a1407851fb..8e4daf0d6791dc7c37b0c6c93ff8557abf87c35f 100644 (file)
@@ -20,6 +20,7 @@
 ###############################################################################
 
 import base64
+import json
 import re
 import ssl
 import socket
@@ -121,18 +122,24 @@ class DDNSSystem(object):
 
                return self._guess_external_ip_address(url, **kwargs)
 
-       def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
+       def send_request(self, url, method="GET", data=None, username=None, password=None,
+                       timeout=30, expect=bytes):
                assert method in ("GET", "POST")
 
-               # Add all arguments in the data dict to the URL and escape them properly.
-               if method == "GET" and data:
-                       query_args = self._format_query_args(data)
-                       data = None
+               # Add all arguments in the data dict to the URL and escape them properly
+               if data:
+                       if method == "GET":
+                               query_args = self._format_query_args(data)
+                               data = None
 
-                       if "?" in url:
-                               url = "%s&%s" % (url, query_args)
-                       else:
-                               url = "%s?%s" % (url, query_args)
+                               if "?" in url:
+                                       url = "%s&%s" % (url, query_args)
+                               else:
+                                       url = "%s?%s" % (url, query_args)
+
+                       # In all other cases, encode any data of type dict() as JSON
+                       elif isinstance(data, dict):
+                               data = json.encode(data)
 
                logger.debug("Sending request (%s): %s" % (method, url))
                if data:
@@ -171,6 +178,10 @@ class DDNSSystem(object):
                        for k, v in resp.info().items():
                                logger.debug("  %s: %s" % (k, v))
 
+                       # If the caller requested JSON, we try to parse the response
+                       if expect == "json":
+                               return json.load(resp)
+
                        # Return the entire response object.
                        return resp