diff --git a/plugins/httpapi/nd.py b/plugins/httpapi/nd.py index ccf0bc5..582a08d 100644 --- a/plugins/httpapi/nd.py +++ b/plugins/httpapi/nd.py @@ -37,6 +37,7 @@ import traceback import mimetypes import tempfile +import sys from ansible.module_utils.six import PY3 from ansible.module_utils._text import to_native, to_text from ansible.module_utils.connection import ConnectionError @@ -261,7 +262,22 @@ def send_file_request(self, method, path, file=None, data=dict(), remote_path=No self.nd.fail_json(msg="Cannot use requests_toolbelt MultipartEncoder() because requests_toolbelt module is not available") mp_encoder = MultipartEncoder(fields=fields) multiheader = {"Content-Type": mp_encoder.content_type, "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br"} - response, rdata = self.connection.send(path, mp_encoder.to_string(), method=method, headers=multiheader) + + if sys.version_info.major == 2: + # For Python 2+ + py2_default_encoding = sys.getdefaultencoding() + reload(sys) + sys.setdefaultencoding("latin-1") # To handle UnicodeDecodeError exception during the send function call + + mp_data = mp_encoder.to_string() + response, rdata = self.connection.send(path, mp_data, method=method, headers=multiheader) + + # Resetting it to the default encoding + if sys.version_info.major == 2: + # For Python 2+ + reload(sys) + sys.setdefaultencoding(py2_default_encoding) + except Exception as e: self.error = dict(code=self.status, message="ND HTTPAPI MultipartEncoder Exception: {0} - {1} ".format(e, traceback.format_exc())) raise ConnectionError(json.dumps(self._verify_response(None, method, path, None)))