[更新]:完整代码
我总是对 pyhton 的静态方法感到困惑,但根据这个(最后一个答案),它应该可以工作!
收到错误:
AttributeError:MyConnection 类没有属性“myuser”
class MyConnection:
def __init__(self, hostname, port, user, password):
myhostname = hostname
myport = port
myuser = user
mypassword = password
isisessid = None
@staticmethod
def connect():
my_session = MyConnection()
headers = {'content-type': 'application/json'}
headers['Authorization'] = 'Basic ' + string.strip(
base64.encodestring(MyConnection.myuser + ':' + MyConnection.mypassword))
body = json.dumps({'username': MyConnection.myuser, 'password': MyConnection.mypassword,
'services': ['platform', 'namespace']})
uri = '/session/1/session'
connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport)
connection.connect()
try:
connection.request('POST', uri, body, headers)
response = connection.getresponse()
my_session.isisessid = MyConnection.extract_session_id(
response.getheaders())
except Exception, e:
print e
connection.close()
except httplib.BadStatusLine, e:
print e
connection.close()
return my_session