From 454f741ef5b56cccd123e12d7b2e6fe31d47c755 Mon Sep 17 00:00:00 2001 From: Toshio Kuratomi Date: Sun, 23 Oct 2016 22:17:06 -0700 Subject: [PATCH] First set of fixes for uri module to work with py3. This fix handles changes in the response headers (no longer all lowercased) and switches from unicode() to to_text(). --- network/basics/uri.py | 48 ++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/network/basics/uri.py b/network/basics/uri.py index 3ecc85ea592..cef369516a4 100644 --- a/network/basics/uri.py +++ b/network/basics/uri.py @@ -20,19 +20,6 @@ # # see examples/playbooks/uri.yml -import cgi -import shutil -import tempfile -import datetime - -try: - import json -except ImportError: - import simplejson as json - -import ansible.module_utils.six as six - - DOCUMENTATION = ''' --- module: uri @@ -217,6 +204,23 @@ EXAMPLES = ''' ''' +import cgi +import datetime +import os +import shutil +import tempfile + +try: + import json +except ImportError: + import simplejson as json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.pycompat24 import get_exception +import ansible.module_utils.six as six +from ansible.module_utils._text import to_text +from ansible.module_utils.urls import fetch_url, url_argument_spec + def write_file(module, url, dest, content): # create a tempfile with some test content @@ -446,11 +450,17 @@ def main(): # Default content_encoding to try content_encoding = 'utf-8' - if 'content_type' in uresp: - content_type, params = cgi.parse_header(uresp['content_type']) + content_type_key = None + for key in uresp: + # Py2: content_type; Py3: Content_type + if 'content_type' == key.lower(): + content_type_key = key + break + if content_type_key is not None: + content_type, params = cgi.parse_header(uresp[content_type_key]) if 'charset' in params: content_encoding = params['charset'] - u_content = unicode(content, content_encoding, errors='replace') + u_content = to_text(content, encoding=content_encoding) if 'application/json' in content_type or 'text/json' in content_type: try: js = json.loads(u_content) @@ -458,7 +468,7 @@ def main(): except: pass else: - u_content = unicode(content, content_encoding, errors='replace') + u_content = to_text(content, encoding=content_encoding) if resp['status'] not in status_code: uresp['msg'] = 'Status code was not %s: %s' % (status_code, uresp.get('msg', '')) @@ -469,9 +479,5 @@ def main(): module.exit_json(changed=changed, **uresp) -# import module snippets -from ansible.module_utils.basic import * -from ansible.module_utils.urls import * - if __name__ == '__main__': main()