Python请求模块和JSON回应 [英] Python Requests Module & JSON Responses
问题描述
我正在使用真棒 请求模块,以测试我为内部项目之一创建的API. 我相信我发现了Requests模块本身的缺陷,或者是我使用该模块的缺陷.
I am using the awesome Requests module to test an API I've created for one of our internal projects. I believe I have discovered what is either a flaw in the Requests module itself, or a flaw in my usage of it.
由于我们的数据不是非常敏感,因此我们的API使用简单的基本HTTP身份验证来控制访问权限.当我使用JSON作为数据格式并使用带有HTTPBasicAuthHandler的urllib2或PHP和cURL来请求API URL时,我会以正确格式的JSON字符串的形式返回数据-没问题.
Because our data is not super sensitive, our API uses simple, basic HTTP authentication to control acces. When I make requests of the API URL, using JSON as the data format and either urllib2 with HTTPBasicAuthHandler or PHP and cURL, I get my data back as a properly formatted JSON string - no problem.
但是,当我使用Requests模块发出相同的请求时,我得到了一个编码字符串,而我无法确定它是哪种编码类型.这是该字符串开头的代码段:
However, when I make the same request using the Requests module, I get back an encoded string, and I cannot determine what type of encoding it is. Here is a snippet of the beginning of that string:
\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xadZ\xfb\x8f\xd3H\x12\xfeWzG\xab;\x90
以下是我与请求一起使用以重现此问题的几行代码:
Here are the few lines of code I am using with Requests to reproduce this issue:
import requests
# api_user and api_pw not printed here for security reasons
r = requests.get('http://ourdomain.com/api/featured/school/json', auth=(api_user, api_pw))
status = r.status_code # Produces 200 every time
rawdata = r.read()
print rawdata
每次我都得到编码字符串.
And I get that encoded string each time I do that.
任何人都可以帮助我确定: a)是什么编码(出于我自己的目的),以及 b)为什么请求"以这种编码返回数据,以及如何对其进行解码和/或修复".
Can anyone help me to determine: a) What encoding that is (for my own edification), and b) Why Requests is returning data in that encoding, and how to decode and/or "fix" it.
提前谢谢!
推荐答案
出于好奇,当您print r.content
时会得到什么?
Out of curiosity, what do you get when you print r.content
?
这篇关于Python请求模块和JSON回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!