问题
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