• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python client.get函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tower_cli.api.client.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: status

    def status(self, pk=None, detail=False, **kwargs):
        """Print the current job status."""
        # Get the job from Ansible Tower.
        debug.log('Asking for project update status.', header='details')
        project = client.get('/projects/%d/' % pk).json()

        # Determine the appropriate project update.
        if 'current_update' in project['related']:
            debug.log('A current update exists; retrieving it.',
                      header='details')
            job = client.get(project['related']['current_update'][7:]).json()
        elif project['related'].get('last_update', None):
            debug.log('No current update exists; retrieving the most '
                      'recent update.', header='details')
            job = client.get(project['related']['last_update'][7:]).json()
        else:
            raise exc.NotFound('No project updates exist.')

        # In most cases, we probably only want to know the status of the job
        # and the amount of time elapsed. However, if we were asked for
        # verbose information, provide it.
        if detail:
            return job

        # Print just the information we need.
        return {
            'elapsed': job['elapsed'],
            'failed': job['failed'],
            'status': job['status'],
        }
开发者ID:jangsutsr,项目名称:tower-cli,代码行数:30,代码来源:project.py


示例2: update

    def update(self, inventory_source, monitor=False, timeout=None, **kwargs):
        """Update the given inventory source."""

        # Establish that we are able to update this inventory source
        # at all.
        debug.log('Asking whether the inventory source can be updated.',
                  header='details')
        r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
        if not r.json()['can_update']:
            raise exc.BadRequest('Tower says it cannot run an update against '
                                 'this inventory source.')

        # Run the update.
        debug.log('Updating the inventory source.', header='details')
        r = client.post('%s%d/update/' % (self.endpoint, inventory_source))

        # If we were told to monitor the project update's status, do so.
        if monitor:
            result = self.monitor(inventory_source, timeout=timeout)
            inventory = client.get('/inventory_sources/%d/' %
                                   result['inventory_source'])\
                              .json()['inventory']
            result['inventory'] = int(inventory)
            return result

        # Done.
        return {'status': 'ok'}
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:27,代码来源:inventory_source.py


示例3: test_auth_error

 def test_auth_error(self):
     """Establish that authentication errors raise the AuthError
     exception.
     """
     with client.test_mode as t:
         t.register('/ping/', 'ERRORED!!', status_code=401)
         with self.assertRaises(exc.AuthError):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例4: test_forbidden_error

 def test_forbidden_error(self):
     """Establish that forbidden errors raise the ForbiddenError
     exception.
     """
     with client.test_mode as t:
         t.register('/ping/', 'ERRORED!!', status_code=403)
         with self.assertRaises(exc.Forbidden):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例5: test_not_found_error

 def test_not_found_error(self):
     """Establish that authentication errors raise the NotFound
     exception.
     """
     with client.test_mode as t:
         t.register('/ping/', 'ERRORED!!', status_code=404)
         with self.assertRaises(exc.NotFound):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例6: test_method_not_allowed_error

 def test_method_not_allowed_error(self):
     """Establish that authentication errors raise the MethodNotAllowed
     exception.
     """
     with client.test_mode as t:
         t.register('/ping/', 'ERRORED!!', status_code=405)
         with self.assertRaises(exc.MethodNotAllowed):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例7: test_bad_request_error

 def test_bad_request_error(self):
     """Establish that other errors not covered above raise the
     BadRequest exception.
     """
     with client.test_mode as t:
         t.register('/ping/', "I'm a teapot!", status_code=418)
         with self.assertRaises(exc.BadRequest):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例8: test_server_error

 def test_server_error(self):
     """Establish that server errors raise the ServerError
     exception as expected.
     """
     with client.test_mode as t:
         t.register('/ping/', 'ERRORED!!', status_code=500)
         with self.assertRaises(exc.ServerError):
             client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:8,代码来源:test_api.py


示例9: test_disable_connection_warning

 def test_disable_connection_warning(self):
     """Establish that the --insecure flag will cause the program to
     call disable_warnings in the urllib3 package.
     """
     with mock.patch('requests.packages.urllib3.disable_warnings') as g:
         with client.test_mode as t:
             t.register('/ping/', "I'm a teapot!", status_code=200)
             with settings.runtime_values(insecure=False):
                 client.get('/ping/')
                 assert g.called
开发者ID:tomfotherby,项目名称:tower-cli,代码行数:10,代码来源:test_api.py


示例10: test_failed_suggestion_protocol

 def test_failed_suggestion_protocol(self):
     """Establish that if connection fails and protocol not given,
     tower-cli suggests that to the user."""
     with settings.runtime_values(verbose=False, host='foo.co'):
         with mock.patch.object(Session, 'request') as req:
             req.side_effect = requests.exceptions.SSLError
             with mock.patch.object(click, 'secho') as secho:
                 with self.assertRaises(exc.ConnectionError):
                     client.get('/ping/')
                 self.assertTrue(secho.called)
开发者ID:ansible,项目名称:tower-cli,代码行数:10,代码来源:test_api.py


示例11: test_connection_ssl_error

 def test_connection_ssl_error(self):
     """Establish that if we get a ConnectionError or an SSLError
     back from requests, that we deal with it nicely.
     """
     for ErrorType in REQUESTS_ERRORS:
         with settings.runtime_values(verbose=False, host='https://foo.co'):
             with mock.patch.object(Session, 'request') as req:
                 req.side_effect = ErrorType
                 with self.assertRaises(exc.ConnectionError):
                     client.get('/ping/')
开发者ID:ansible,项目名称:tower-cli,代码行数:10,代码来源:test_api.py


示例12: update

    def update(self, inventory_source, monitor=False, wait=False,
               timeout=None, **kwargs):
        """Update the given inventory source.

        =====API DOCS=====
        Update the given inventory source.

        :param inventory_source: Primary key or name of the inventory source to be updated.
        :type inventory_source: str
        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update
                        rather than exiting with a success.
        :type monitor: bool
        :param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is
                     in progress.
        :type wait: bool
        :param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
                        of seconds.
        :type timeout: int
        :param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching
                           an inventory update.
        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
                  call if ``wait`` flag is on; dictionary of "status" if none of the two flags are on.
        :rtype: dict
        :raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.

        =====API DOCS=====
        """

        # Establish that we are able to update this inventory source
        # at all.
        debug.log('Asking whether the inventory source can be updated.', header='details')
        r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
        if not r.json()['can_update']:
            raise exc.BadRequest('Tower says it cannot run an update against this inventory source.')

        # Run the update.
        debug.log('Updating the inventory source.', header='details')
        r = client.post('%s%d/update/' % (self.endpoint, inventory_source), data={})
        inventory_update_id = r.json()['inventory_update']

        # If we were told to monitor the project update's status, do so.
        if monitor or wait:
            if monitor:
                result = self.monitor(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
            elif wait:
                result = self.wait(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
            inventory = client.get('/inventory_sources/%d/' % result['inventory_source']).json()['inventory']
            result['inventory'] = int(inventory)
            return result

        # Done.
        return {
            'id': inventory_update_id,
            'status': 'ok'
        }
开发者ID:ansible,项目名称:tower-cli,代码行数:55,代码来源:inventory_source.py


示例13: test_connection_ssl

 def test_connection_ssl(self):
     with client.test_mode as t:
         t.register_json('/ping/', {'status': 'ok'})
         https_adapter = client.adapters['https://']
         with mock.patch.object(FauxAdapter, 'send', wraps=https_adapter.send) as mock_send:
             client.get('/ping/')
             mock_send.assert_called_once_with(
                 mock.ANY, cert=None, proxies=mock.ANY, stream=mock.ANY,
                 timeout=mock.ANY, verify=True
             )
             self.assertTrue(mock_send.call_args[1]['verify'])
开发者ID:ansible,项目名称:tower-cli,代码行数:11,代码来源:test_api.py


示例14: test_connection_ssl_error_verbose

 def test_connection_ssl_error_verbose(self):
     """Establish that if we get a ConnectionError or an SSLError
     back from requests, that we deal with it nicely, and
     additionally print the internal error if verbose is True.
     """
     for ErrorType in REQUESTS_ERRORS:
         with settings.runtime_values(verbose=True, host='https://foo.co'):
             with mock.patch.object(Session, 'request') as req:
                 req.side_effect = ErrorType
                 with mock.patch.object(debug, 'log') as dlog:
                     with self.assertRaises(exc.ConnectionError):
                         client.get('/ping/')
                     self.assertEqual(dlog.call_count, 5)
开发者ID:ansible,项目名称:tower-cli,代码行数:13,代码来源:test_api.py


示例15: list

    def list(self, root=False, **kwargs):
        """Return a list of groups."""

        # Option to list children of a parent group
        if kwargs.get('parent', None):
            self.set_child_endpoint(
                parent=kwargs['parent'],
                inventory=kwargs.get('inventory', None)
            )
            kwargs.pop('parent')

        # Sanity check: If we got `--root` and no inventory, that's an
        # error.
        if root and not kwargs.get('inventory', None):
            raise exc.UsageError('The --root option requires specifying an '
                                 'inventory also.')

        # If we are tasked with getting root groups, do that.
        if root:
            inventory_id = kwargs['inventory']
            r = client.get('/inventories/%d/root_groups/' % inventory_id)
            return r.json()

        # Return the superclass implementation.
        return super(Resource, self).list(**kwargs)
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:25,代码来源:group.py


示例16: list

    def list(self, **kwargs):
        """Return a list of objects.

        =====API DOCS=====
        Retrieve a list of Tower settings.

        :param category: The category slug in which to look up indevidual settings.
        :type category: str
        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.
        :returns: A JSON object containing details of all resource objects returned by Tower backend.
        :rtype: dict

        =====API DOCS=====
        """
        self.custom_category = kwargs.get('category', 'all')
        try:
            result = super(Resource, self).list(**kwargs)
        except exc.NotFound as e:
            categories = map(
                lambda category: category['slug'],
                client.get('/settings/').json()['results']
            )
            e.message = '%s is not a valid category.  Choose from [%s]' % (
                kwargs['category'],
                ', '.join(categories)
            )
            raise e
        finally:
            self.custom_category = None
        return {
            'results': [{'id': k, 'value': v} for k, v in result.items()]
        }
开发者ID:ansible,项目名称:tower-cli,代码行数:32,代码来源:setting.py


示例17: version

def version():
    """Display full version information."""

    # Print out the current version of Tower CLI.
    click.echo('Tower CLI %s' % __version__)

    # Print out the current API version of the current code base.
    click.echo('API %s' % CUR_API_VERSION)

    # Attempt to connect to the Ansible Tower server.
    # If we succeed, print a version; if not, generate a failure.
    try:
        r = client.get('/config/')
    except RequestException as ex:
        raise exc.TowerCLIError('Could not connect to Ansible Tower.\n%s' %
                                six.text_type(ex))
    config = r.json()
    license = config.get('license_info', {}).get('license_type', 'open')
    if license == 'open':
        server_type = 'AWX'
    else:
        server_type = 'Ansible Tower'
    click.echo('%s %s' % (server_type, config['version']))

    # Print out Ansible version of server
    click.echo('Ansible %s' % config['ansible_version'])
开发者ID:ansible,项目名称:tower-cli,代码行数:26,代码来源:misc.py


示例18: status

    def status(self, pk=None, detail=False, **kwargs):
        """Print the current job status. This is used to check a running job.
        You can look up the job with the same parameters used for a get
        request."""
        # Remove default values (anything where the value is None).
        self._pop_none(kwargs)

        # Search for the record if pk not given
        if not pk:
            job = self.get(include_debug_header=True, **kwargs)
        # Get the job from Ansible Tower if pk given
        else:
            debug.log('Asking for job status.', header='details')
            finished_endpoint = '%s%d/' % (self.endpoint, pk)
            job = client.get(finished_endpoint).json()

        # In most cases, we probably only want to know the status of the job
        # and the amount of time elapsed. However, if we were asked for
        # verbose information, provide it.
        if detail:
            return job

        # Print just the information we need.
        return adict({
            'elapsed': job['elapsed'],
            'failed': job['failed'],
            'status': job['status'],
        })
开发者ID:ashmanpan,项目名称:tower-cli,代码行数:28,代码来源:base.py


示例19: update

    def update(self, pk=None, create_on_missing=False, monitor=False,
               timeout=None, name=None, organization=None):
        """Trigger a project update job within Ansible Tower.
        Only meaningful on non-manual projects.
        """
        # First, get the appropriate project.
        # This should be uniquely identified at this point, and if not, then
        # we just want the error that `get` will throw to bubble up.
        project = self.get(pk, name=name, organization=organization)
        pk = project['id']

        # Determine whether this project is able to be updated.
        debug.log('Asking whether the project can be updated.',
                  header='details')
        result = client.get('/projects/%d/update/' % pk)
        if not result.json()['can_update']:
            raise exc.CannotStartJob('Cannot update project.')

        # Okay, this project can be updated, according to Tower.
        # Commence the update.
        debug.log('Updating the project.', header='details')
        result = client.post('/projects/%d/update/' % pk)

        # If we were told to monitor the project update's status, do so.
        if monitor:
            return self.monitor(pk, timeout=timeout)

        # Return the project update ID.
        return {
            'changed': True,
        }
开发者ID:jangsutsr,项目名称:tower-cli,代码行数:31,代码来源:project.py


示例20: callback

    def callback(self, pk=None, host_config_key='', extra_vars=None):
        """Contact Tower and request a configuration update using this job template.

        =====API DOCS=====
        Contact Tower and request a provisioning callback using this job template.

        :param pk: Primary key of the job template to run provisioning callback against.
        :type pk: int
        :param host_config_key: Key string used to authenticate the callback host.
        :type host_config_key: str
        :param extra_vars: Extra variables that are passed to provisioning callback.
        :type extra_vars: array of str
        :returns: A dictionary of a single key "changed", which indicates whether the provisioning callback
                  is successful.
        :rtype: dict

        =====API DOCS=====
        """
        url = self.endpoint + '%s/callback/' % pk
        if not host_config_key:
            host_config_key = client.get(url).json()['host_config_key']
        post_data = {'host_config_key': host_config_key}
        if extra_vars:
            post_data['extra_vars'] = parser.process_extra_vars(list(extra_vars), force_json=True)
        r = client.post(url, data=post_data, auth=None)
        if r.status_code == 201:
            return {'changed': True}
开发者ID:ansible,项目名称:tower-cli,代码行数:27,代码来源:job_template.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python client.post函数代码示例发布时间:2022-05-27
下一篇:
Python tower_cli.get_resource函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap