Python 3 Gzip json for post on an API

Python 3 Gzip json for post on an API

使用 python 3

获取 gzip 压缩的 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 需要 gzipped 附件。如果我尝试按原样发​​送 JSON,API 会吐回 "The HTTP request is invalid. Reason: Invalid JSON attachment:Not in GZIP format"。

我尝试了 gzip.compress,但它说:内存视图:需要一个类似字节的对象,而不是 'str'

所以我尝试了 gzip.compress(json.dumps(raw_json).encode('utf-8')) 并且说 Object of type bytes is not 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)