token.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. from aliyunsdkcore.client import AcsClient
  3. from aliyunsdkcore.request import CommonRequest
  4. from .exception import GetTokenFailed
  5. import json
  6. __all__ = ['getToken']
  7. def getToken(akid, aksecret, domain='cn-shanghai',
  8. version='2019-02-28',
  9. url='nls-meta.cn-shanghai.aliyuncs.com'):
  10. """
  11. Help methods to get token from aliyun by giving access id and access secret
  12. key
  13. Parameters:
  14. -----------
  15. akid: str
  16. access id from aliyun
  17. aksecret: str
  18. access secret key from aliyun
  19. domain: str:
  20. default is cn-shanghai
  21. version: str:
  22. default is 2019-02-28
  23. url: str
  24. full url for getting token, default is
  25. nls-meta.cn-shanghai.aliyuncs.com
  26. """
  27. if akid is None or aksecret is None:
  28. raise GetTokenFailed('No akid or aksecret')
  29. client = AcsClient(akid, aksecret, domain)
  30. request = CommonRequest()
  31. request.set_method('POST')
  32. request.set_domain(url)
  33. request.set_version(version)
  34. request.set_action_name('CreateToken')
  35. response = client.do_action_with_exception(request)
  36. response_json = json.loads(response)
  37. if 'Token' in response_json:
  38. token = response_json['Token']
  39. if 'Id' in token:
  40. return token['Id']
  41. else:
  42. raise GetTokenFailed(f'Missing id field in token:{token}')
  43. else:
  44. raise GetTokenFailed(f'Token not in response:{response_json}')