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

Python debug.log函数代码示例

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

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



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

示例1: 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


示例2: _get_auth_token

 def _get_auth_token(self):
     filename = os.path.expanduser('~/.tower_cli_token.json')
     token_json = None
     try:
         with open(filename) as f:
             token_json = json.load(f)
         if not isinstance(token_json, dict) or self.cli_client.get_prefix() not in token_json or \
                 'token' not in token_json[self.cli_client.get_prefix()] or \
                 'expires' not in token_json[self.cli_client.get_prefix()] or \
                 dt.utcnow() > dt.strptime(token_json[self.cli_client.get_prefix()]['expires'], TOWER_DATETIME_FMT):
             raise Exception("Current token expires.")
         return 'Token ' + token_json[self.cli_client.get_prefix()]['token']
     except Exception as e:
         debug.log('Acquiring and caching auth token due to:\n%s' % str(e), fg='blue', bold=True)
         if not isinstance(token_json, dict):
             token_json = {}
         token_json[self.cli_client.get_prefix()] = self._acquire_token()
         if not isinstance(token_json[self.cli_client.get_prefix()], dict) or \
                 'token' not in token_json[self.cli_client.get_prefix()] or \
                 'expires' not in token_json[self.cli_client.get_prefix()]:
             raise exc.AuthError('Invalid Tower auth token format: %s' % json.dumps(
                 token_json[self.cli_client.get_prefix()]
             ))
         with open(filename, 'w') as f:
             json.dump(token_json, f)
         try:
             os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR)
         except Exception as e:
             warnings.warn(
                 'Unable to set permissions on {0} - {1} '.format(filename, e),
                 UserWarning
             )
         return 'Token ' + token_json[self.cli_client.get_prefix()]['token']
开发者ID:ansible,项目名称:tower-cli,代码行数:33,代码来源:api.py


示例3: delete

    def delete(self, pk=None, fail_on_missing=False, **kwargs):
        """Remove the given object.

        If `fail_on_missing` is True, then the object's not being found is
        considered a failure; otherwise, a success with no change is reported.
        """
        # If we weren't given a primary key, determine which record we're
        # deleting.
        if not pk:
            existing_data = self._lookup(fail_on_missing=fail_on_missing,
                                         **kwargs)
            if not existing_data:
                return {'changed': False}
            pk = existing_data['id']

        # Attempt to delete the record.
        # If it turns out the record doesn't exist, handle the 404
        # appropriately (this is an okay response if `fail_on_missing` is
        # False).
        url = '%s%d/' % (self.endpoint, pk)
        debug.log('DELETE %s' % url, fg='blue', bold=True)
        try:
            client.delete(url)
            return {'changed': True}
        except exc.NotFound:
            if fail_on_missing:
                raise
            return {'changed': False}
开发者ID:ashmanpan,项目名称:tower-cli,代码行数:28,代码来源:base.py


示例4: convert

    def convert(self, value, param, ctx):
        """Return the appropriate interger value. If a non-integer is
        provided, attempt a name-based lookup and return the primary key.
        """
        resource = tower_cli.get_resource(self.resource_name)

        # Ensure that None is passed through without trying to
        # do anything.
        if value is None:
            return None

        # If we were already given an integer, do nothing.
        # This ensures that the convert method is idempotent.
        if isinstance(value, int):
            return value

        # Do we have a string that contains only digits?
        # If so, then convert it to an integer and return it.
        if re.match(r'^[\d]+$', value):
            return int(value)

        # Okay, we have a string. Try to do a name-based lookup on the
        # resource, and return back the ID that we get from that.
        #
        # This has the chance of erroring out, which is fine.
        try:
            debug.log('The %s field is given as a name; '
                      'looking it up.' % param.name, header='details')
            rel = resource.get(**{resource.unique_criterion: value})
        except exc.TowerCLIError as ex:
            raise exc.RelatedError('Could not get %s. %s' %
                                   (self.resource_name, str(ex)))

        # Done! Return the ID.
        return rel['id']
开发者ID:Glavnyuk,项目名称:tower-cli,代码行数:35,代码来源:types.py


示例5: create

    def create(self, organization=None, monitor=False, timeout=None,
               *args, **kwargs):
        """Create a new item of resource, with or w/o org.
        This would be a shared class with user, but it needs the ability
        to monitor if the flag is set.
        """
        backup_endpoint = self.endpoint
        if organization:
            debug.log("using alternative endpoint specific to organization",
                      header='details')

            # Get the organization from Tower, will lookup name if needed
            org_resource = get_resource('organization')
            org_data = org_resource.get(organization)
            org_pk = org_data['id']

            self.endpoint = '/organizations/%s%s' % (org_pk, backup_endpoint)
        answer = super(Resource, self).create(*args, **kwargs)
        self.endpoint = backup_endpoint

        # if the monitor flag is set, wait for the SCM to update
        if monitor:
            project_id = answer['id']
            return self.monitor(project_id, timeout=timeout)

        return answer
开发者ID:ashmanpan,项目名称:tower-cli,代码行数:26,代码来源:project.py


示例6: create

    def create(self, organization=None, monitor=False, timeout=None,
               fail_on_found=False, force_on_exists=False,
               **kwargs):
        """Create a new item of resource, with or w/o org.
        This would be a shared class with user, but it needs the ability
        to monitor if the flag is set.
        """
        # First, run the create method, ignoring the organization given
        answer = super(Resource, self).write(
            create_on_missing=True,
            fail_on_found=fail_on_found, force_on_exists=force_on_exists,
            **kwargs
        )
        project_id = answer['id']

        # If an organization is given, associate it here
        if organization:

            # Get the organization from Tower, will lookup name if needed
            org_resource = get_resource('organization')
            org_data = org_resource.get(organization)
            org_pk = org_data['id']

            debug.log("associating the project with its organization",
                      header='details', nl=1)
            org_resource._assoc('projects', org_pk, project_id)

        # if the monitor flag is set, wait for the SCM to update
        if monitor:
            return self.monitor(project_id, timeout=timeout)

        return answer
开发者ID:digideskio,项目名称:tower-cli,代码行数:32,代码来源:project.py


示例7: 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


示例8: 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


示例9: list

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

        If one or more filters are provided through keyword arguments,
        filter the results accordingly.

        If no filters are provided, return all results.
        """
        # If the `all_pages` flag is set, then ignore any page that might
        # also be sent.
        if all_pages:
            kwargs.pop('page', None)

        # Get the response.
        debug.log('Getting records.', header='details')
        response = self.read(**kwargs)

        # Alter the "next" and "previous" to reflect simple integers,
        # rather than URLs, since this endpoint just takes integers.
        for key in ('next', 'previous'):
            if not response[key]:
                continue
            match = re.search(r'page=(?P<num>[\d]+)', response[key])
            response[key] = int(match.groupdict()['num'])

        # If we were asked for all pages, keep retrieving pages until we
        # have them all.
        if all_pages and response['next']:
            cursor = copy(response)
            while cursor['next']:
                cursor = self.list(**dict(kwargs, page=cursor['next']))
                response['results'] += cursor['results']

        # Done; return the response
        return response
开发者ID:ashmanpan,项目名称:tower-cli,代码行数:35,代码来源:base.py


示例10: test_not_verbose_mode

 def test_not_verbose_mode(self):
     """Establish that this method does nothing if we are not in
     verbose mode.
     """
     with settings.runtime_values(verbose=False):
         with mock.patch.object(click, 'secho') as secho:
             debug.log('foo bar baz')
             self.assertEqual(secho.call_count, 0)
开发者ID:Robinjtu,项目名称:tower-cli,代码行数:8,代码来源:test_utils_debug.py


示例11: launch

    def launch(self, monitor=False, wait=False, timeout=None, **kwargs):
        """Launch a new ad-hoc command.

        Runs a user-defined command from Ansible Tower, immediately starts it,
        and returns back an ID in order for its status to be monitored.

        =====API DOCS=====
        Launch a new ad-hoc command.

        :param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather
                        than exiting with a success.
        :type monitor: bool
        :param wait: Flag that if set, monitor the status of the job, but do not print while job 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 needed to create and launch an ad hoc command.
        :returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
                  call if ``wait`` flag is on; dictionary of "id" and "changed" if none of the two flags are on.
        :rtype: dict
        :raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.

        =====API DOCS=====
        """
        # This feature only exists for versions 2.2 and up
        r = client.get('/')
        if 'ad_hoc_commands' not in r.json():
            raise exc.TowerCLIError('Your host is running an outdated version'
                                    'of Ansible Tower that can not run '
                                    'ad-hoc commands (2.2 or earlier)')

        # Pop the None arguments because we have no .write() method in
        # inheritance chain for this type of resource. This is needed
        self._pop_none(kwargs)

        # Actually start the command.
        debug.log('Launching the ad-hoc command.', header='details')
        result = client.post(self.endpoint, data=kwargs)
        command = result.json()
        command_id = command['id']

        # If we were told to monitor the command once it started, then call
        # monitor from here.
        if monitor:
            return self.monitor(command_id, timeout=timeout)
        elif wait:
            return self.wait(command_id, timeout=timeout)

        # Return the command ID and other response data
        answer = OrderedDict((
            ('changed', True),
            ('id', command_id),
        ))
        answer.update(result.json())
        return answer
开发者ID:ansible,项目名称:tower-cli,代码行数:56,代码来源:ad_hoc.py


示例12: create

 def create(self, **kwargs):
     if (kwargs.get('user', False) or kwargs.get('team', False) or
             kwargs.get('organization', False)):
         debug.log('Checking Project API Details.', header='details')
         r = client.options('/credentials/')
         if 'organization' in r.json()['actions']['POST']:
             for i in range(len(self.fields)):
                 if self.fields[i].name in ('user', 'team', 'credential'):
                     self.fields[i].no_lookup = True
     return super(Resource, self).create(**kwargs)
开发者ID:ghjm,项目名称:tower-cli,代码行数:10,代码来源:credential.py


示例13: test_extra_newlines

 def test_extra_newlines(self):
     """Establish that extra newlines are correctly applied if they
     are requested.
     """
     s = 'All your base are belong to us.'
     with mock.patch.object(click, 'secho') as secho:
         with settings.runtime_values(verbose=True):
             debug.log(s, nl=3)
         self.assertEqual(secho.mock_calls[0][1][0],
                          'All your base are belong to us.\n\n')
开发者ID:Robinjtu,项目名称:tower-cli,代码行数:10,代码来源:test_utils_debug.py


示例14: get

 def get(self, pk=None, **kwargs):
     """Get information about a role."""
     if kwargs.pop('include_debug_header', True):
         debug.log('Getting the role record.', header='details')
     data, self.endpoint = self.data_endpoint(kwargs)
     response = self.read(pk=pk, fail_on_no_results=True,
                          fail_on_multiple_results=True, **data)
     item_dict = response['results'][0]
     self.configure_display(item_dict)
     return item_dict
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:10,代码来源:role.py


示例15: 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


示例16: test_header

 def test_header(self):
     """Establish that a header echoes the expected string, of
     correct length.
     """
     s = 'Decided all the things.'
     with mock.patch.object(click, 'secho') as secho:
         with settings.runtime_values(verbose=True):
             debug.log(s, header='decision', fg='blue')
         self.assertEqual(secho.mock_calls[0][1][0],
                          '*** DECISION: Decided all the things. '
                          '*****************************************')
开发者ID:Robinjtu,项目名称:tower-cli,代码行数:11,代码来源:test_utils_debug.py


示例17: get_permission_pk

 def get_permission_pk(self, pk, user, team, **kwargs):
     """Return the pk with a search method specific to permissions."""
     if not pk:
         self.set_base_url(user, team)
         debug.log('Checking for existing permission.', header='details')
         existing_data = self._lookup(
             fail_on_found=False, fail_on_missing=True,
             include_debug_header=False, **kwargs)
         return existing_data['id']
     else:
         self.no_lookup_flag = True
         return pk
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:12,代码来源:permission.py


示例18: get

    def get(self, pk=None, **kwargs):
        """Return one and exactly one object.

        Lookups may be through a primary key, specified as a positional
        argument, and/or through filters specified through keyword arguments.

        If the number of results does not equal one, raise an exception.
        """
        if kwargs.pop("include_debug_header", True):
            debug.log("Getting the record.", header="details")
        response = self.read(pk=pk, fail_on_no_results=True, fail_on_multiple_results=True, **kwargs)
        return response["results"][0]
开发者ID:Robinjtu,项目名称:tower-cli,代码行数:12,代码来源:base.py


示例19: create

 def create(self, *args, **kwargs):
     """Create a project, with or w/o org.
     Fix for issue #52, second method, replacing the /projects/
     endpoint temporarily if the project has an organization specified
     """
     if "organization" in kwargs:
         debug.log("using alternative endpoint for new project",
                   header='details')
         org_pk = kwargs['organization']
         self.endpoint = '/organizations/%s/projects/' % org_pk
     to_return = super(Resource, self).create(*args, **kwargs)
     self.endpoint = '/projects/'
     return to_return
开发者ID:tomfotherby,项目名称:tower-cli,代码行数:13,代码来源:project.py


示例20: test_extra_long_words

 def test_extra_long_words(self):
     """Ensure we treat words longer than 79 characters properly and do not
     trigger any issue.
     """
     s = ' '.join(['short_word', 'short_word', 'l' + 'o' * 68 + 'ng_word'])
     expected = '\n'.join([
         '*** DETAILS: short_word short_word ********************************************',
         '*** loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_word ',
     ])
     with mock.patch.object(click, 'secho') as secho:
         with settings.runtime_values(verbose=True):
             debug.log(s, header='details')
         self.assertEqual(secho.mock_calls[0][1][0], expected)
开发者ID:ansible,项目名称:tower-cli,代码行数:13,代码来源:test_utils_debug.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python tox.cmdline函数代码示例发布时间:2022-05-27
下一篇:
Python settings.runtime_values函数代码示例发布时间: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