如何使 Content-Encoding: deflate 可读?

问题描述

我正在创建一个 Python 脚本,以便在远程服务器的指标很高时发送警报。服务器正在使用以网络服务器模式运行的 Glances 库,而我的本地机器正在向服务器的端点发送请求。

我的请求从端点 /api/3/cpu/total 获得响应,但是当我输出此响应的内容时,它以字节为单位,当转换为字符串时,这不是我在 curling 时得到的响应.

我已经查看了与我的情况相关的以前的答案,但我发现的答案要么是很久以前的,要么与文本输出无关。

我的功能

def call_endpoint(machine,endpoint):
    url = "http://" + machine + ":3101" + endpoint
    headers = {"Content-Type": "application/json; charset=utf-8","Accept": "application/json"}
    try:
        response = requests.get(url=url,headers=headers)
        print(response.content)
        return response.json()
    except requests.HTTPError as http_err:
        print(http_err)

来自响应的标题

{
    "Date":"Wed,10 Feb 2021 14:27:02 GMT","Server":"WsgiServer/0.2 cpython/3.8.5","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,POST,PUT,OPTIONS","Access-Control-Allow-Headers":"Origin,Accept,Content-Type,X-Requested-With,X-CSRF-Token","Content-Type":"application/json; charset=utf-8","content-encoding":"deflate","Content-Length":"31"
}

函数的响应

b"x\x9c\xabV*\xc9/I\xccQ\xb2R0\xd03\xaf\x05\x00#'\x04P"

来自curling

的回应
{"total": 1.9}

解决方法

我添加了标题:

"Accept-Encoding": "gzip"

我现在收到了 dict 回复。

希望这对未来的人有用!