ctms_api.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import ujson
  4. import requests
  5. class CtmsApi(object):
  6. def __init__(self, user, password, url):
  7. self.user = user
  8. self.password = password
  9. self.url = url
  10. def __call__(self, path, params=None, body=None):
  11. token = self.generate_token()
  12. print('获取Token:', token)
  13. if not params:
  14. params = {'access_token': token}
  15. else:
  16. params['access_token'] = token
  17. resp = requests.post('%s%s' % (self.url, path), params=params, json=body, timeout=30)
  18. if resp.status_code == 200:
  19. result = resp.text
  20. if result:
  21. return ujson.loads(result)
  22. elif resp.status_code == 401:
  23. print('ctms token invalidate')
  24. return {'code': resp.status_code, 'message': '401 Forbidden'}
  25. else:
  26. print('ctms error with unknown code: %d' % resp.status_code)
  27. return {'code': resp.status_code, 'message': None}
  28. def generate_token(self):
  29. """
  30. 生成token,token一般只需生成一次即可,有效期一年,
  31. 之后每次获取到的token值均相同,除非使用刷新token接口,
  32. 此处为方便,每次调用接口时都获取token,实际不建议这么做,
  33. 如果对安全性要求比较高,可以每隔几小时刷新一次token,
  34. 否则获取一次以后设置为常量即可
  35. """
  36. body = {
  37. 'userName': self.user,
  38. 'password': self.password
  39. }
  40. response = requests.post(url=self.url + '/user/generate_access_token/v2', json=body, timeout=30)
  41. if response.status_code != 200:
  42. return ''
  43. result = response.text
  44. if not result:
  45. return ''
  46. json_result = ujson.loads(result)
  47. data = json_result.get('data')
  48. if not data:
  49. return ''
  50. return data.get('accessToken')