python requests equivalent to curl -H

删除回忆录丶 提交于 2020-01-15 08:22:10

问题


I'm trying to subscribe to an event stream coming from my particle photon. The docs suggest

curl -H "Authorization: Bearer {ACCESS_TOKEN_GOES_HERE}" \
https://api.particle.io/v1/events/motion-detected

I've tried

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'access_token': access_token}
r3 = requests.get(address3,params=data)

but I get nothing, and I mean nothing, in response

I expect a response like:

event: motion-detected
data: {"data":"intact","ttl":"60","published_at":"2015-06-25T05:08:22.136Z","coreid":"coreid"}

event: motion-detected
data: {"data":"broken","ttl":"60","published_at":"2015-06-25T05:08:23.014Z","coreid":"coreid"}

I just don't understand what curl is doing relative to what requests is doing. Thanks for the help, JR


回答1:


Custom headers are passed as a dictionary in headers argument

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'Authorization': 'Bearer {ACCESS_TOKEN_GOES_HERE}'}
r3 = requests.get(address3, headers=data)

params argument is used to pass URL parameters. Basically your code issues a request to https://api.particle.io/v1/events/motion-detected?access_token=token_goes_here, this can be veriefied by printing url print(r3.url)




回答2:


As stated in Alik's response, custom headers are passed as a dictionary in the headers argument. In your case, that would be

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'Authorization': 'Bearer ' + access_token}
r3 = requests.get(address3, headers=data)

Since this is authentication, the cleanest way would be to implement a custom authentication handler that set this header as described in the documentation.



来源:https://stackoverflow.com/questions/31041994/python-requests-equivalent-to-curl-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!