From: Michael Tremer Date: Fri, 29 Aug 2025 22:05:46 +0000 (+0000) Subject: system: Add native support for JSON requests and responses X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=84ffb6ee71d9ccd45aef43b03c5ad7dc03551e7a;p=ddns.git system: Add native support for JSON requests and responses Signed-off-by: Michael Tremer --- diff --git a/src/ddns/system.py b/src/ddns/system.py index 48c9a8f..8e4daf0 100644 --- a/src/ddns/system.py +++ b/src/ddns/system.py @@ -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