コード例 #1
0
ファイル: http.py プロジェクト: xuweiliang/Codelibrary
    def encode_headers(headers):
        """Encodes headers.

        Note: This should be used right before
        sending anything out.

        :param headers: Headers to encode
        :returns: Dictionary with encoded headers'
                  names and values
        """
        return dict((strutils.safe_encode(h), strutils.safe_encode(v))
                    for h, v in six.iteritems(headers))
コード例 #2
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.NotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(strutils.safe_encode(name_or_id))
        return manager.get(name_or_id)
    except (ValueError, exc.NotFound):
        pass

    # finally try to find entity by name
    matches = list(manager.list(filters={'name': name_or_id}))
    num_matches = len(matches)
    if num_matches == 0:
        msg = "No %s with a name or ID of '%s' exists." % \
              (manager.resource_class.__name__.lower(), name_or_id)
        raise exc.CommandError(msg)
    elif num_matches > 1:
        msg = ("Multiple %s matches found for '%s', use an ID to be more"
               " specific." %
               (manager.resource_class.__name__.lower(), name_or_id))
        raise exc.CommandError(msg)
    else:
        return matches[0]
コード例 #3
0
ファイル: http.py プロジェクト: xuweiliang/Codelibrary
    def log_curl_request(self, method, url, headers, data, kwargs):
        curl = ['curl -i -X %s' % method]

        headers = copy.deepcopy(headers)
        headers.update(self.session.headers)

        for (key, value) in six.iteritems(headers):
            header = '-H \'%s: %s\'' % safe_header(key, value)
            curl.append(header)

        if not self.session.verify:
            curl.append('-k')
        else:
            if isinstance(self.session.verify, six.string_types):
                curl.append(' --cacert %s' % self.session.verify)

        if self.session.cert:
            curl.append(' --cert %s --key %s' % self.session.cert)

        if data and isinstance(data, six.string_types):
            curl.append('-d \'%s\'' % data)

        curl.append(url)

        msg = ' '.join([strutils.safe_encode(item, errors='ignore')
                        for item in curl])
        LOG.debug(msg)
コード例 #4
0
def print_dict(d, max_column_width=80):
    pt = prettytable.PrettyTable(['Property', 'Value'], caching=False)
    pt.align = 'l'
    pt.max_width = max_column_width
    for k, v in six.iteritems(d):
        if isinstance(v, (dict, list)):
            v = json.dumps(v)
        pt.add_row([k, v])
    print(strutils.safe_encode(pt.get_string(sortby='Property')))
コード例 #5
0
def exception_to_str(exc):
    try:
        error = six.text_type(exc)
    except UnicodeError:
        try:
            error = str(exc)
        except UnicodeError:
            error = ("Caught '%(exception)s' exception." % {
                "exception": exc.__class__.__name__
            })
    return strutils.safe_encode(error, errors='ignore')
コード例 #6
0
ファイル: http.py プロジェクト: xuweiliang/Codelibrary
 def log_http_response(resp, body=None):
     status = (resp.raw.version / 10.0, resp.status_code, resp.reason)
     dump = ['\nHTTP/%.1f %s %s' % status]
     headers = resp.headers.items()
     dump.extend(['%s: %s' % safe_header(k, v) for k, v in headers])
     dump.append('')
     if body:
         body = strutils.safe_decode(body)
         dump.extend([body, ''])
     LOG.debug('\n'.join([strutils.safe_encode(x, errors='ignore')
                          for x in dump]))
コード例 #7
0
def print_list(objs, fields, formatters=None, field_settings=None):
    formatters = formatters or {}
    field_settings = field_settings or {}
    pt = prettytable.PrettyTable([f for f in fields], caching=False)
    pt.align = 'l'

    for o in objs:
        row = []
        for field in fields:
            if field in field_settings:
                for setting, value in six.iteritems(field_settings[field]):
                    setting_dict = getattr(pt, setting)
                    setting_dict[field] = value

            if field in formatters:
                row.append(formatters[field](o))
            else:
                field_name = field.lower().replace(' ', '_')
                data = getattr(o, field_name, None) or ''
                row.append(data)
        pt.add_row(row)

    print(strutils.safe_encode(pt.get_string()))
コード例 #8
0
def exit(msg=''):
    if msg:
        print(strutils.safe_encode(msg), file=sys.stderr)
    sys.exit(1)