def poli_request(self, endpoint, data, method="POST"):
"""
@arg : endpoint The API target endpoint
@arg : data dictionary
@return : dict issued from JSON
"""
if not self.is_online:
g_logger.error("Cannot send requests while not connected")
raise IOError
headers = {"Accept-encoding": "gzip, deflate",
"Content-type": "application/json",
"Accept": "*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "Keep-Alive",
"X-API-Key": self.api_key}
json_data = json.dumps(data)
try:
self.h_conn.request(method, endpoint, json_data, headers)
except httplib.CannotSendRequest as e:
g_logger.error("Error during request, retrying")
self.close_connection()
self.get_online()
self.h_conn.request(method, endpoint, json_data, headers)
res = self.h_conn.getresponse()
if res.status != 200:
g_logger.error("The %s request didn't go as expected", method)
g_logger.debug("Status code was %d and content was %s",
res.status, res.read())
return None
content_type = res.getheader("Content-Encoding")
if content_type == "gzip":
buf = StringIO(res.read())
res = gzip.GzipFile(fileobj=buf)
data = res.read()
try:
result = json.loads(data)
except BaseException:
raise IOError
return result
评论列表
文章目录