python实现rest请求api示例

2019-10-06 17:35:40于丽

    # return '&'.join(args)

    args = []
    _urlencode = kw.pop('_urlencode', urllib.quote)
    for k, v in _format_params(_pk=None, encode=_urlencode, **kw):
        args.append('%s=%s' % (k, v))

    args = sorted(args, key=lambda s: s.split("=")[0])
    return '&'.join(args)


def _read_body(obj):
    using_gzip = obj.headers.get('Content-Encoding', '') == 'gzip'
    body = obj.read()
    if using_gzip:
        gzipper = gzip.GzipFile(fileobj=StringIO(body))
        fcontent = gzipper.read()
        gzipper.close()
        return fcontent
    return body


class JsonDict(dict):
    """
    general json object that allows attributes to be bound to and also behaves like a dict
    """

    def __getattr__(self, attr):
        try:
            return self[attr]
        except KeyError:
            raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)

    def __setattr__(self, attr, value):
        self[attr] = value


def _parse_json(s):
    """
    parse str into JsonDict
    """

    def _obj_hook(pairs):
        """
        convert json object to python object
        """
        o = JsonDict()
        for k, v in pairs.iteritems():
            o[str(k)] = v
        return o
    return json.loads(s, object_hook=_obj_hook)


def _parse_xml(s):
    """
    parse str into xml
    """

    raise NotImplementedError()


def _parse_html(s):
    """
    parse str into html
    """

    raise NotImplementedError()


def _parse_text(s):
    """
    parse str into text
    """

    raise NotImplementedError()


def _http_call(the_url, method, return_type="json", request_type=None, request_suffix=None, headers={}, _timeout=30, **kwargs):
    """