当前位置: 首页>>代码示例>>Python>>正文


Python urls.open_url方法代码示例

本文整理汇总了Python中ansible.module_utils.urls.open_url方法的典型用法代码示例。如果您正苦于以下问题:Python urls.open_url方法的具体用法?Python urls.open_url怎么用?Python urls.open_url使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ansible.module_utils.urls的用法示例。


在下文中一共展示了urls.open_url方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: install_with_makepkg

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def install_with_makepkg(module, package, extra_args, skip_pgp_check, ignore_arch):
    """
    Install the specified package with makepkg
    """
    module.get_bin_path('fakeroot', required=True)
    f = open_url('https://aur.archlinux.org/rpc/?v=5&type=info&arg={}'.format(urllib.parse.quote(package)))
    result = json.loads(f.read().decode('utf8'))
    if result['resultcount'] != 1:
        return (1, '', 'package {} not found'.format(package))
    result = result['results'][0]
    f = open_url('https://aur.archlinux.org/{}'.format(result['URLPath']))
    with tempfile.TemporaryDirectory() as tmpdir:
        tar = tarfile.open(mode='r|*', fileobj=f)
        tar.extractall(tmpdir)
        tar.close()
        command = build_command_prefix('makepkg', extra_args, skip_pgp_check=skip_pgp_check, ignore_arch=ignore_arch)
        rc, out, err = module.run_command(command, cwd=os.path.join(tmpdir, result['Name']), check_rc=True)
    return (rc, out, err) 
开发者ID:kewlfft,项目名称:ansible-aur,代码行数:20,代码来源:aur.py

示例2: _authorize

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def _authorize(self, username, password):
        def request_token(url):
            resp = open_url(
                url,
                method=HTTPMethod.POST,
                data=json.dumps({'grant_type': 'password', 'username': username, 'password': password}),
                headers=BASE_HEADERS,
                validate_certs=False
            ).read()
            return json.loads(to_text(resp))

        api_versions = sorted(self._fetch_api_versions(), reverse=True)

        for version in api_versions:
            token_url = self._hostname + self.TOKEN_PATH_TEMPLATE.format(version)
            try:
                token = request_token(token_url)
            except urllib_error.HTTPError as e:
                logger.debug("Can't get token for API version: %s", version, exc_info=True)
                if e.code != HTTPStatus.UNAUTHORIZED:
                    raise
            else:
                return token

        raise Exception("Can't fetch token via API") 
开发者ID:CiscoDevNet,项目名称:FTDAnsible,代码行数:27,代码来源:build.py

示例3: amp_api_call

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def amp_api_call(module, x_biscotti, set_cookie, host, api_name, method='GET', data={}, params=None):
    url = "https://" + str(host) + "/" + str(api_name)
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    client_cert= module.params.get('client_cert')
    client_key= module.params.get('client_key')
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib'
    try:
        if method == "GET":
            if params:
                params = urlencode(params)
                url= url + "?" + params
            headers = { 'Cookie' : 'MercuryAuthHandlerCookie_AMPAuth=' + set_cookie }
            resp = open_url(url, headers=headers, validate_certs=validate_certs)

        else: # POST
            headers = {'Cookie' : 'MercuryAuthHandlerCookie_AMPAuth=' + set_cookie, 'X-BISCOTTI' : x_biscotti }
            resp = open_url(url, headers=headers, method=method, validate_certs=validate_certs, data=data, client_cert=client_cert, client_key=client_key)

    except Exception as e:
        module.fail_json(changed=False, msg="API Call failed! Exception during api call", reason=str(e))
    return resp 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:25,代码来源:arubaairwave_config.py

示例4: login_activate

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def login_activate(module, credential_0, credential_1):
    set_cookie = ""
    resp = ""
    url = "https://activate.arubanetworks.com/LOGIN"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': 'Activate-cookie.text'}
    data = {"credential_0": credential_0 ,"credential_1": credential_1 }
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    try:
        resp = open_url(url=url, data=urlencode(data), headers=headers, method="POST", validate_certs=validate_certs, cookies=cookies)
        if resp.code == 200:
            cookie_list = []
            for ck in cookies:
                cookie_list.append(str(ck.name) + "="+ str(ck.value))
            set_cookie = "; ".join(cookie_list)
        else:
            module.fail_json(changed=False, msg="Login Failed!", reason=resp.read(),
                response="HTTP status_code: " + str(resp.code))
    except Exception as e:
        module.fail_json(changed=False, msg="API Call failed! Exception during login", reason=str(e))
    return set_cookie 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:23,代码来源:arubaactivate_config.py

示例5: grafana_list_dashboards

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def grafana_list_dashboards(self):
        # define http headers
        headers = self.grafana_headers()

        dashboard_list = []
        try:
            if self.search:
                r = open_url('%s/api/search?query=%s' % (self.grafana_url, self.search), headers=headers, method='GET')
            else:
                r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET')
        except HTTPError as e:
            raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e))
        if r.getcode() == 200:
            try:
                dashboard_list = json.loads(r.read())
            except Exception as e:
                raise GrafanaAPIException('Unable to parse json list %s' % to_native(e))
        else:
            raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode()))

        return dashboard_list 
开发者ID:ansible-collections,项目名称:community.grafana,代码行数:23,代码来源:grafana_dashboard.py

示例6: _fetch_api_versions

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def _fetch_api_versions(self):
        try:
            # In case of 6.2.3 when Api Versions resource does not exists HTTP 401 will be returned
            resp = open_url(
                self._hostname + self.API_VERSIONS_PATH,
                method=HTTPMethod.GET,
                headers=BASE_HEADERS,
                validate_certs=False
            ).read()
            supported_versions = json.loads(to_text(resp))["supportedVersions"]
        except Exception:
            logger.debug("Can't fetch supported API versions", exc_info=True)
            supported_versions = self.SUPPORTED_VERSIONS

        return supported_versions 
开发者ID:CiscoDevNet,项目名称:FTDAnsible,代码行数:17,代码来源:build.py

示例7: _send_request

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def _send_request(self, url_path, method):
        url = self._hostname + url_path
        response = open_url(url, method=method, headers=self._auth_headers, validate_certs=False).read()
        return json.loads(to_text(response)) 
开发者ID:CiscoDevNet,项目名称:FTDAnsible,代码行数:6,代码来源:build.py

示例8: login_amp

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def login_amp(module, host, credential_0, credential_1):
    return_list = []
    resp = ""
    url = "https://" + str(host) + "/LOGIN"
    headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'}
    data = 'credential_0=' + credential_0 + '&credential_1=' + credential_1 + '&destination=/&login=Log In'
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    client_cert= module.params.get('client_cert')
    client_key= module.params.get('client_key')
    try:

        resp = open_url(url, headers=headers, method="POST", validate_certs=validate_certs, data=data, cookies=cookies, client_cert=client_cert, client_key=client_key)
        if resp.code == 200:
            ## Extract Biscotti from headers
            if "X-BISCOTTI" in resp.headers:
                x_biscotti = resp.headers.get("X-BISCOTTI")
                return_list.append(x_biscotti)
            ## Extract session key from cookie
            for set_cookie in cookies:
                set_cookie = set_cookie.value
                return_list.append(set_cookie)

        else:
            module.fail_json(changed=False, msg="Login Failed!", reason=resp.text,
                response="HTTP status_code: " + str(resp.status_code))
    except Exception as e:
        module.fail_json(changed=False, msg="API Call failed! Exception during login", reason=str(e))
    return return_list 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:31,代码来源:arubaairwave_config.py

示例9: login_cppm

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def login_cppm(module, host, client_id, client_secret):
    resp = ""
    access_token = ""
    url = "https://" + str(host) + ":443/api/oauth"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    data = {"grant_type": "client_credentials","client_id": client_id,"client_secret": client_secret}
    module.api_call['url'] = url # Store the url to module, so we can print the details in case of error
    module.api_call['login_data'] = data
    validate_certs=module.params.get('validate_certs')
    client_cert=module.params.get('client_cert')
    client_key=module.params.get('client_key')
    try:
        resp = open_url(url=url, data=json.dumps(data), headers=headers, method="POST", validate_certs=validate_certs,
                        client_cert=client_cert, client_key=client_key)
        if resp.code == 200:
            result = json.loads(resp.read())
            access_token = result["access_token"]
        else:
            module.fail_json(changed=False, msg="Login Failed!", reason="",
                api_call=module.api_call, response="HTTP status_code: " + str(resp.code) + " content: " +
                resp.read())
    except Exception as e:
        if resp == "": # Exception during http request, we have no response
             module.fail_json(changed=False, msg="API Call failed! Exception during login", reason=str(e),
                api_call=module.api_call)
        else:
            module.fail_json(changed=False, msg="API Call failed! Exception during login", reason=str(e),
                api_call=module.api_call, response="http status: " + str(resp.code) + " content: " + resp.read())
    return access_token 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:31,代码来源:arubaclearpass_config.py

示例10: login_api_mm

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def login_api_mm(module):
    # Define variables from module arguments
    host = module.params.get('host')
    username = module.params.get('username')
    password = module.params.get('password')
    session_key = ""
    resp = ""
    # Variables required for open_url
    url = "https://" + str(host) + ":4343/rest/login"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    data = {'user': username, 'passwd': password}
    data = json.dumps(data)
    cookies = cookiejar.LWPCookieJar()
    validate_certs = False
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib2'
    method = "POST"

    module.api_call = {'host':host,'user':username,'passwd':password, 'url':''}
    module.api_call['url'] = url # Stores the url to module, so we can print the details in case of error

    try:
        resp = open_url(url, data=data, headers=headers, method=method, validate_certs=validate_certs, http_agent=http_agent, follow_redirects=follow_redirects, cookies=cookies)
        resp = resp.read()
        result = json.loads(resp)

        if result['Status'] == "Success":
            session_key = result['sid']
        else:
            module.fail_json(changed=False, msg="Login Failed! Check the credentials you provided", reason=str(result), api_call=module.api_call, response="content: " + str(resp) + " login status code: " + str(result['status']) + " login error: " + str(result['status_str']))

    except Exception as e:
        module.fail_json(changed=False, msg="API Call failed! Exception during login", reason=str(e), api_call=module.api_call)

    session_dict = {'host':host,
                   'session_token': session_key}
    return session_dict 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:39,代码来源:arubainstant_config.py

示例11: grafana_switch_organisation

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def grafana_switch_organisation(self, headers):
        try:
            r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST')
        except HTTPError as e:
            raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, to_native(e)))
        if r.getcode() != 200:
            raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode()))) 
开发者ID:ansible-collections,项目名称:community.grafana,代码行数:9,代码来源:grafana_dashboard.py

示例12: cppm_api_call

# 需要导入模块: from ansible.module_utils import urls [as 别名]
# 或者: from ansible.module_utils.urls import open_url [as 别名]
def cppm_api_call(module, host, access_token, api_name, method='GET', data={}):
    url = "https://" + str(host) + ":443/api/" + str(api_name)
    module.api_call['url'] = url # Store the url to module, so we can print the details in case of error
    headers = ""
    resp = ""
    variableID = ""
    hard_list = ["user_id", "name", "mac_address"]
    validate_certs=module.params.get('validate_certs')
    client_cert=module.params.get('client_cert')
    client_key=module.params.get('client_key')
    try:
        if method == "GET" or method == "DELETE":
            headers = {'Accept': 'application/json', 'Authorization': "Bearer " + access_token}
            resp = open_url(url=url, headers=headers, method=method, validate_certs=validate_certs, 
                            client_cert=client_cert, client_key=client_key)
        else: # POST, PATCH
            headers = {'Accept': 'application/json', 'Content-Type': 'application/json',
                          'Authorization': "Bearer " + access_token}
            resp = open_url(url=url, data=json.dumps(data), headers=headers, method=method, validate_certs=validate_certs,
                            client_cert=client_cert, client_key=client_key)
        return resp
    except Exception as e:
        if "422" in str(e):
            if method == "POST":
                try:
                    for ele in data.keys():
                        if ele in hard_list:
                            variableID = ele
                            break
                    if variableID:
                        ##### Convert _ to -
                        varIDEdit = variableID.replace("_", "-")
                        url = "https://" + str(host) + ":443/api/" + str(api_name) + "/" + str(varIDEdit) + "/" + data[variableID]
                        resp = open_url(url=url, data=json.dumps(data), headers=headers, method="PATCH", validate_certs=validate_certs,
                                        client_cert=client_cert, client_key=client_key)
                        return resp
                    else:
                        module.exit_json(skipped=True, msg=str(e) + "...Entry might exists on ClearPass")
                except Exception as err:
                    module.exit_json(skipped=True, msg=str(err) + "...Entry might exists on ClearPass")
        else:
            module.fail_json(changed=False, msg="API Call failed! Exception during api call", reason=str(e),
                api_call=module.api_call) 
开发者ID:aruba,项目名称:aruba-ansible-modules,代码行数:45,代码来源:arubaclearpass_config.py


注:本文中的ansible.module_utils.urls.open_url方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。