2017-05-26 54 views
0

因此,我正在研究Python脚本以与Heroku API进行通信以获取dyno信息,但它似乎不适用于Python。然而,具有完全相同的信息,它的卷曲正常工作:Heroku API仅在Python中返回403

作品(卷曲7.51.0):

curl -XGET -H 'Authorization: Bearer <BEARER>' -H 'Accept: application/vnd.heroku+json; version=3' 'https://api.heroku.com/apps/<APP>/dynos/<DYNO>' 

失败(Python中,无论是在2.7.12,3.5.3和3.6。 1):

import json 
import requests 
callapi = requests.get('https://api.heroku.com/apps/<APP>/dynos/<DYNO>', headers={"Authorization":"Bearer <BEARER>", "Accept":"application/vnd.heroku+json; version=3"}) 
json = callapi.json() 
print(json) 

...错误:

{'id': 'forbidden', 'message': 'You do not have access to the app <APP>.'} 

哪里<APP>是我的应用程序的名字,<DYNO>为t他的动态名称,而<BEARER>是我的不记名令牌。

任何帮助,将不胜感激!

+0

调试完毕后它似乎像Heroku的CLI试图重写提供与Heroku的帐户的一个登录到CLI。在另一台机器上做这件事纠正了这个问题。 – HeyItsShuga

回答

0

的问题是,requests使用.netrc文件,如果没有提供auth说法:http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#netrc-authentication

所以requests正在使用您的Heroku凭证(heroku login保存在该文件的凭据)。

一个简单的方法来解决问题,在这里expained:http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#new-forms-of-authentication

TL; DR:删除Authorization头,并使用auth参数与自定义类。

这是我使用的实现:

class HerokuBearerAuth(requests.auth.AuthBase): 
    def __init__(self, api_key): 
     self.api_key = api_key 

    def __call__(self, r): 
     r.headers.update({'Authorization': 'Bearer {}'.format(self.api_key)}) 
     return r 

myHeaders = {'Accept': 'application/vnd.heroku+json; version=3'} 
response = requests.get(myUrl, headers=myHeaders, auth=HerokuBearerAuth(api_key))