2017-06-22 10 views
1

私はたぶん単純なものを見落としていると言って前置きしましょう。Pythonを使用してBluemix CF APIを認証する方法

私はPythonとCF APIを使ってBluemixアカウントの操作をスクリプト化しようとしています。

まずその後のOAuthトークンを取得するためにauthorization_endpointに投稿https://login.ng.bluemix.net/UAALoginServerWAR/

response = requests.get('https://api.ng.bluemix.net/info') 

、authorization_endpointを取得するためにhttps://api.ng.bluemix.net/infoに着きます。

results = response.json() 
auth_endpoint = results['authorization_endpoint'] + 'oauth/token?grant_type=password&client=cf' 
http_payload = { 
    'username': id, 
    'password': pw, 
    'client_id': 'cf' 
    } 
auth = ('cf', '') 
response = requests.post(auth_endpoint, data=http_payload, auth=auth) 

そこでこの場合https://api.ng.bluemix.net/v2/organizationsには、CFのAPIを呼び出すために返されたOAuthのトーク​​ンを使用しています。

results = response.json() 
url = 'https://api.ng.bluemix.net/v2/organizations' 
authorization = results['token_type'] + ' ' + results['access_token'] 
http_headers = { 
    'accept': 'application/json', 
    'content-type': 'application/json', 
    'authorization': authorization 
    } 
response = requests.get(url, headers=http_headers) 

しかし、これは404、{ "説明": "不明要求"、 "ERROR_CODE": "CF-NOTFOUND"、 "コード":10000}になります。これは正しいアプローチですか?私は何を見落としていますか?

答えて

1

これが私の作品:

id = 'changeme' 
pw = 'changeme' 

import json 
import urllib 
import requests 

response = requests.get('https://api.ng.bluemix.net/info') 
results = response.json() 
auth_endpoint = results['authorization_endpoint'] + '/oauth/token' 

data = 'grant_type=password&username={0}&password={1}'.format(id, pw) 
auth = ('cf', '') 
headers = { 
    'accept': 'application/json', 
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8' 
    } 
response = requests.post(auth_endpoint, data=data, headers=headers, auth=auth) 

results = response.json() 
url = 'https://api.ng.bluemix.net/v2/organizations' 
authorization = results['token_type'] + ' ' + results['access_token'] 
http_headers = { 
    'accept': 'application/json', 
    'content-type': 'application/json', 
    'authorization': authorization 
    } 
response = requests.get(url, headers=http_headers) 

print(response.text) 

戻り値:

{ 
    "total_results": 6, 
    "total_pages": 1, 
    "prev_url": null, 
    "next_url": null, 
    "resources": [ 
    ... 
} 
+0

おかげで、はい。これも私のために働く。私は誤った場所を探していた。私はそれがどのようにトークンを生成しているのかと考えていました。しかし、カールコマンドで作業するためのアクセス権を取得した後、私のエラーはより簡単で愚かなタイプミスであることに気付きました。私が使用したURLはhttps:\\ api.ng.bluemix.net \ V2 \でした。ある時点で、私は「v」を大文字にすることができました。 – user2085050

関連する問題