Python 3 Gzip json for post on an API



在使用python 3获取gziped的JSON有效负载时遇到一些麻烦

def post_data ( data ) :
method_name = json.loads(data)['subject'][4][0][1]
instance = json.loads(data)['serialNumber']
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
utc_now = datetime.datetime.utcnow().strftime("%m-%d-%Y %H:%M:%S")
not_after = datetime.datetime.strptime(json.loads(data)['notAfter'], "%b %d %H:%M:%S %Y GMT" ).strftime("%m-%d-%Y %H:%M:%S")
days =  datetime.datetime.strptime(not_after, "%m-%d-%Y %H:%M:%S")-
datetime.datetime.strptime(utc_now, "%m-%d-%Y %H:%M:%S")
values = days.days
raw_json = '''{"MetricReports":[{
"Metadata":{
"MinPeriod":"FiveMinute",
"MaxPeriod":"FiveMinute"
},
"Namespace":"Schema/Service",
"Metrics":[{
"Dimensions":{
"DataSet":"NONE",
"Marketplace":"PDX",
"HostGroup":"ALL",
"Host":"host.com",
"ServiceName":"Server",
"MethodName":"%s",
"Client":"ALL",
"MetricClass":"instance",
"Instance":"%s"
},
"MetricName":"daysToExpiry",
"Timestamp":"%s",
"Type":"MetricsLine",
"Unit":"None",
"Values":%s
}
]}
]}''' %(method_name, instance, timestamp, values)

headers = {'content-type' : 'application/x-gzip'}
putUrl = 'http://api-pdx.com/'
session = boto3.Session()
credentials = session.get_credentials()
region = 'us-west-2'
service = 'monitor-api'
auth = AWS4Auth(
credentials.access_key,
credentials.secret_key,
region,
service,
session_token = credentials.token)
r = requests.post(url = putUrl, json = gzip.compress(raw_json) , auth = auth, headers = headers, verify=False)
print(r.content)
get_data()
post_data(data)

我需要压缩raw_json,因为 API 需要一个压缩的附件。 API 正在吐槽"HTTP 请求无效。原因:无效的 JSON 附件:不是 GZIP 格式",如果我尝试按原样发送 JSON。

我尝试了gzip.compress,但它说:memoryview:需要一个类似字节的对象,而不是"str">

所以我尝试了gzip.compress(json.dumps(raw_json(.encode('utf-8'((,并且说字节类型的对象不是JSON可序列化的

要使用requests.post方法发送二进制数据,它们应作为data参数传递,而不是作为json传递:

requests.post(url = putUrl,
data = gzip.compress(json.dumps(raw_json).encode('utf-8')),
auth = auth,
headers = headers,
verify=False)

相关内容

最新更新