如何使用Python对Bluemix CF API进行身份验证
让我先说一句,我可能忽略了一些简单的事情 我正试图用Python和CFAPI为我的Bluemix帐户编写一些操作脚本 首先,获取授权\u端点 然后发布到authorization_端点以获取oauth令牌如何使用Python对Bluemix CF API进行身份验证,python,api,oauth,ibm-cloud,cloud-foundry,Python,Api,Oauth,Ibm Cloud,Cloud Foundry,让我先说一句,我可能忽略了一些简单的事情 我正试图用Python和CFAPI为我的Bluemix帐户编写一些操作脚本 首先,获取授权\u端点 然后发布到authorization_端点以获取oauth令牌 results = response.json() auth_endpoint = results['authorization_endpoint'] + 'oauth/token?grant_type=password&client=cf' http_payload = {
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)
然后,在本例中,使用返回的oauth令牌调用CF API
但这将导致404,{“description”:“未知请求”,“错误代码”:“CF NotFound”,“code”:10000}。这是正确的方法吗?我忽略了什么?这对我很有用:
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": [
...
}
谢谢,是的。这对我也有用。我找错地方了。我以为这是我生成代币的方式。但在使用curl命令后,我意识到我的错误是一个更简单、愚蠢的打字错误。我使用的URL是https:\\api.ng.bluemix.net\V2\。在某个时候,我设法将“v”大写。
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": [
...
}