首页 > 解决方案 > 如何使 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"

curl来自ing的回应

{"total": 1.9}

标签: pythonpython-requestsdeflate

解决方案


我添加了标题:

"Accept-Encoding": "gzip"

dict现在得到了回应。

希望这对将来的某人有用!


推荐阅读