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
评论列表
文章目录