I'm creating a Python script to send alerts when a remote server's metrics are high. The server is using the Glances library running in webserver mode and my local machine is sending requests to the server's endpoints.
My requests get a response from the endpoint /api/3/cpu/total
but when I output the content of this response it's in bytes, which when converted to a string, isn't the response I get when curl
ing.
I've looked at previous answers relating to my situation but the ones I found are either from a long time ago or aren't relevant to a text output.
My Function
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)
Headers from Response
{
"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"
}
Response from Function
b"x\x9c\xabV*\xc9/I\xccQ\xb2R0\xd03\xaf\x05\x00#'\x04P"
Response from curl
ing
{"total": 1.9}
I added the header:
"Accept-Encoding": "gzip"
And I get a dict
response now.
Hope this is useful to someone in the future!