Vthon中的Rest API的VCloud Director Org用户身份验证

时间:2012-07-09 12:41:22

标签: python authentication vmware vcloud-director-rest-api

我有VMware设置进行测试。我创建了一个用户abc / abc123来访问组织URL“http:// localhost / cloud / org / MyOrg”。我想访问VCloud的RestAPI。我在 firefox 中尝试使用 RestClient 插件。它的工作正常。

现在我尝试使用python代码。

url = 'https://localhost/api/sessions/'
req = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % ('abc@MyOrg', 'abc123'))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
req.add_header("Accept", 'application/*+xml;version=1.5')

f = urllib2.urlopen(req)
data = f.read()
print(data)

这是我从stackoverflow获得的代码。但是对于我的例子,它给出了“urllib2.HTTPError:HTTP Error 403:Forbidden”错误。

我也尝试过同样的HTTP身份验证。

1 个答案:

答案 0 :(得分:5)

在做了一些谷歌搜索后,我找到了帖子https://stackoverflow.com/a/6348729/243031的解决方案。我更改了可用性的代码。我发布了答案,因为如果有人有同样的错误,他会直接得到答案。

我的更改代码是:

import urllib2
import base64

# make a string with the request type in it:
method = "POST"
# create a handler. you can specify different handlers here (file uploads etc)
# but we go for the default
handler = urllib2.HTTPSHandler()
# create an openerdirector instance
opener = urllib2.build_opener(handler)
# build a request
url = 'https://localhost/api/sessions'
request = urllib2.Request(url)
# add any other information you want
base64string = base64.encodestring('%s:%s' % ('abc@MyOrg', 'abc123'))[:-1]
authheader =  "Basic %s" % base64string
request.add_header("Authorization", authheader)
request.add_header("Accept",'application/*+xml;version=1.5')

# overload the get method function with a small anonymous function...
request.get_method = lambda: method
# try it; don't forget to catch the result
try:
    connection = opener.open(request)
except urllib2.HTTPError,e:
    connection = e

# check. Substitute with appropriate HTTP code.
if connection.code == 200:
    data = connection.read()
    print "Data :", data
else:
    print "ERRROR", connection.code

希望这可以帮助那些想要在没有数据的情况下发送 POST 请求的人。