client.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # -*- coding: utf-8 -*-
  2. import Tea
  3. import json
  4. import uuid
  5. import platform
  6. import socket
  7. import time
  8. from io import BytesIO
  9. from datetime import datetime
  10. try:
  11. from urllib import urlencode
  12. except ImportError:
  13. from urllib.parse import urlencode
  14. from Tea.converter import TeaConverter
  15. from Tea.model import TeaModel
  16. from Tea.stream import READABLE
  17. class Client(object):
  18. """
  19. This is a utility module
  20. """
  21. class _ModelEncoder(json.JSONEncoder):
  22. def default(self, o):
  23. if isinstance(o, TeaModel):
  24. return o.to_map()
  25. elif isinstance(o, bytes):
  26. return TeaConverter.to_str(o)
  27. super(Client._ModelEncoder, self).default(o)
  28. @staticmethod
  29. def __read_part(f, size=1024):
  30. while True:
  31. part = f.read(size)
  32. if part:
  33. yield part
  34. else:
  35. return
  36. @staticmethod
  37. def __get_default_agent():
  38. return 'AlibabaCloud (%s;%s) Python/%s Core/%s TeaDSL/1' % (
  39. platform.system(), platform.machine(), platform.python_version(), Tea.__version__
  40. )
  41. @staticmethod
  42. def to_bytes(val):
  43. """
  44. Convert a string(utf8) to bytes
  45. @return: the return bytes
  46. """
  47. return TeaConverter.to_bytes(val)
  48. @staticmethod
  49. def to_string(val):
  50. """
  51. Convert a bytes to string(utf8)
  52. @return: the return string
  53. """
  54. return TeaConverter.to_string(val)
  55. @staticmethod
  56. def parse_json(val):
  57. """
  58. Parse it by JSON format
  59. @return: the parsed result
  60. """
  61. try:
  62. return json.loads(val)
  63. except ValueError:
  64. raise RuntimeError('Failed to parse the value as json format, Value: "%s".' % TeaConverter.to_str(val))
  65. @staticmethod
  66. def read_as_bytes(stream):
  67. """
  68. Read data from a readable stream, and compose it to a bytes
  69. @param stream: the readable stream
  70. @return: the bytes result
  71. """
  72. if isinstance(stream, TeaConverter.basestring):
  73. return TeaConverter.to_bytes(stream)
  74. else:
  75. b = ''
  76. for part in Client.__read_part(stream, 1024):
  77. b += part
  78. return b
  79. @staticmethod
  80. def read_as_string(stream):
  81. """
  82. Read data from a readable stream, and compose it to a string
  83. @param stream: the readable stream
  84. @return: the string result
  85. """
  86. buff = Client.read_as_bytes(stream)
  87. return Client.to_string(buff)
  88. @staticmethod
  89. def read_as_json(stream):
  90. """
  91. Read data from a readable stream, and parse it by JSON format
  92. @param stream: the readable stream
  93. @return: the parsed result
  94. """
  95. return Client.parse_json(Client.read_as_string(stream))
  96. @staticmethod
  97. def get_nonce():
  98. """
  99. Generate a nonce string
  100. @return: the nonce string
  101. """
  102. name = socket.gethostname() + str(uuid.uuid1())
  103. namespace = uuid.NAMESPACE_URL
  104. return str(uuid.uuid5(namespace, name))
  105. @staticmethod
  106. def get_date_utcstring():
  107. """
  108. Get an UTC format string by current date, e.g. 'Thu, 06 Feb 2020 07:32:54 GMT'
  109. @return: the UTC format string
  110. """
  111. return datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
  112. @staticmethod
  113. def default_string(real, default):
  114. """
  115. If not set the real, use default value
  116. @return: the return string
  117. """
  118. return real if real is not None else default
  119. @staticmethod
  120. def default_number(real, default):
  121. """
  122. If not set the real, use default value
  123. @return: the return number
  124. """
  125. return real if real is not None else default
  126. @staticmethod
  127. def to_form_string(val):
  128. """
  129. Format a map to form string, like a=a%20b%20c
  130. @return: the form string
  131. """
  132. if not val:
  133. return ""
  134. keys = sorted(list(val))
  135. dic = [(k, TeaConverter.to_str(val[k])) for k in keys if not isinstance(val[k], READABLE)]
  136. return urlencode(dic)
  137. @staticmethod
  138. def to_jsonstring(val):
  139. """
  140. Stringify a value by JSON format
  141. @return: the JSON format string
  142. """
  143. if isinstance(val, str):
  144. return str(val)
  145. return json.dumps(val, cls=Client._ModelEncoder)
  146. @staticmethod
  147. def empty(val):
  148. """
  149. Check the string is empty?
  150. @return: if string is null or zero length, return true
  151. """
  152. return not val
  153. @staticmethod
  154. def equal_string(val1, val2):
  155. """
  156. Check one string equals another one?
  157. @return: if equals, return true
  158. """
  159. return val1 == val2
  160. @staticmethod
  161. def equal_number(val1, val2):
  162. """
  163. Check one number equals another one?
  164. @return: if equals, return true
  165. """
  166. return val1 == val2
  167. @staticmethod
  168. def is_unset(value):
  169. """
  170. Check one value is unset
  171. @return: if unset, return true
  172. """
  173. return value is None
  174. @staticmethod
  175. def stringify_map_value(m):
  176. """
  177. Stringify the value of map
  178. @return: the new stringified map
  179. """
  180. if m is None:
  181. return {}
  182. dic_result = {}
  183. for k, v in m.items():
  184. if v is not None:
  185. v = TeaConverter.to_string(v)
  186. dic_result[k] = v
  187. return dic_result
  188. @staticmethod
  189. def anyify_map_value(m):
  190. """
  191. Anyify the value of map
  192. @return: the new anyfied map
  193. """
  194. return m
  195. @staticmethod
  196. def assert_as_boolean(value):
  197. """
  198. Assert a value, if it is a boolean, return it, otherwise throws
  199. @return: the boolean value
  200. """
  201. if not isinstance(value, bool):
  202. raise ValueError('%s is not a bool' % TeaConverter.to_str(value))
  203. return value
  204. @staticmethod
  205. def assert_as_string(value):
  206. """
  207. Assert a value, if it is a string, return it, otherwise throws
  208. @return: the string value
  209. """
  210. if not isinstance(value, TeaConverter.unicode):
  211. raise ValueError('%s is not a string' % TeaConverter.to_str(value))
  212. return value
  213. @staticmethod
  214. def assert_as_bytes(value):
  215. """
  216. Assert a value, if it is a bytes, return it, otherwise throws
  217. @return: the bytes value
  218. """
  219. if not isinstance(value, bytes):
  220. raise ValueError('%s is not a bytes' % TeaConverter.to_str(value))
  221. return value
  222. @staticmethod
  223. def assert_as_number(value):
  224. """
  225. Assert a value, if it is a number, return it, otherwise throws
  226. @return: the number value
  227. """
  228. if not isinstance(value, TeaConverter.number):
  229. raise ValueError('%s is not a number' % TeaConverter.to_str(value))
  230. return value
  231. @staticmethod
  232. def assert_as_map(value):
  233. """
  234. Assert a value, if it is a map, return it, otherwise throws
  235. @return: the map value
  236. """
  237. if not isinstance(value, dict):
  238. raise ValueError('%s is not a dict' % TeaConverter.to_str(value))
  239. return value
  240. @staticmethod
  241. def get_user_agent(user_agent):
  242. """
  243. Get user agent, if it userAgent is not null, splice it with defaultUserAgent and return, otherwise return defaultUserAgent
  244. @return: the string value
  245. """
  246. if user_agent:
  247. return '%s %s' % (
  248. Client.__get_default_agent(), user_agent
  249. )
  250. return Client.__get_default_agent()
  251. @staticmethod
  252. def is_2xx(code):
  253. """
  254. If the code between 200 and 300, return true, or return false
  255. @return: boolean
  256. """
  257. return 200 <= code < 300
  258. @staticmethod
  259. def is_3xx(code):
  260. """
  261. If the code between 300 and 400, return true, or return false
  262. @return: boolean
  263. """
  264. return 300 <= code < 400
  265. @staticmethod
  266. def is_4xx(code):
  267. """
  268. If the code between 400 and 500, return true, or return false
  269. @return: boolean
  270. """
  271. return 400 <= code < 500
  272. @staticmethod
  273. def is_5xx(code):
  274. """
  275. If the code between 500 and 600, return true, or return false
  276. @return: boolean
  277. """
  278. return 500 <= code < 600
  279. @staticmethod
  280. def validate_model(m):
  281. """
  282. Validate model
  283. @return: void
  284. """
  285. if isinstance(m, TeaModel):
  286. m.validate()
  287. @staticmethod
  288. def to_map(in_):
  289. """
  290. Model transforms to map[string]any
  291. @return: map[string]any
  292. """
  293. if isinstance(in_, TeaModel):
  294. return in_.to_map()
  295. else:
  296. return in_
  297. @staticmethod
  298. def sleep(millisecond):
  299. """
  300. Suspends the current thread for the specified number of milliseconds.
  301. """
  302. time.sleep(millisecond / 1000)
  303. @staticmethod
  304. def to_array(input):
  305. """
  306. Transform input as array.
  307. """
  308. if input is None:
  309. return []
  310. out = []
  311. for i in input:
  312. if isinstance(i, TeaModel):
  313. out.append(i.to_map())
  314. else:
  315. out.append(i)
  316. return out
  317. @staticmethod
  318. def assert_as_readable(value):
  319. """
  320. Assert a value, if it is a readable, return it, otherwise throws
  321. @return: the readable value
  322. """
  323. if isinstance(value, TeaConverter.basestring):
  324. value = BytesIO(TeaConverter.to_bytes(value))
  325. if not isinstance(value, READABLE):
  326. raise ValueError('The value is not a readable')
  327. return value
  328. @staticmethod
  329. def assert_as_array(value):
  330. """
  331. Assert a value, if it is a array, return it, otherwise throws
  332. @return the array value
  333. """
  334. if not isinstance(value, list):
  335. raise ValueError('The value is not a list')
  336. return value