restutils.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:gae-python-cookiecutter 作者: txomon 项目源码 文件源码
def http_request(method, url, data=None, json=None, headers=None):
    body = None
    if not headers:
        headers = {}
    if json and isinstance(json, dict):
        headers['Content-Type'] = 'application/json'
        body = _json.dumps(json)
    elif data and isinstance(data, dict):
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        body = urlencode(data)
    if method not in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']:
        raise Exception('Method %s is not supported' % method)
    try:
        parsed_url = urlsplit(url)
        assert isinstance(parsed_url, SplitResult)
        if parsed_url.scheme == 'https':
            connection = httplib.HTTPSConnection
        elif parsed_url.scheme == 'http':
            connection = httplib.HTTPConnection
        conn = connection(parsed_url.netloc)
        conn.request(
            method,
            '{}?{}'.format(parsed_url.path, parsed_url.query),
            body,
            headers
        )
        res = conn.getresponse()
        res_headers = dict(res.getheaders())
        res_code = res.status
        res_body = res.read()
    except Exception:
        logger.exception('Something happened while processing the request')
        raise Exception('Http request failed')
    return res_body, res_code, res_headers
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号