Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. class ApiError(Exception):
  2.  
  3. def __init__(self, request, response):
  4. super().__init__(f"{repr(request)} -> {repr(response)}")
  5. self.request = request
  6. self.response = response
  7.  
  8.  
  9. class Api:
  10.  
  11. API_URL = "api.exmo.com"
  12. API_VERSION = "v1"
  13. REQUESTS_PER_MINUTE = 180
  14.  
  15. def __init__(self, key, secret, timeout):
  16. self._key = key
  17. self._secret = secret.encode("utf-8")
  18. self._timeout = timeout
  19. self._last_call = None
  20.  
  21. def _sha512(self, data):
  22. h = hmac.new(key=self._secret, digestmod=hashlib.sha512)
  23. h.update(data.encode("utf-8"))
  24. return h.hexdigest()
  25.  
  26. def __getattr__(self, name):
  27. return functools.partial(self._call, name)
  28.  
  29. def _call(self, name, **params):
  30. now = time.monotonic()
  31. if self._last_call:
  32. delta = 60 / self.REQUESTS_PER_MINUTE + self._last_call - now
  33. time.sleep(max(0, delta))
  34. self._last_call = now
  35. params["nonce"] = int(round(time.time() * 1000))
  36. encoded_params = urllib.parse.urlencode(params)
  37. headers = {
  38. "Content-type": "application/x-www-form-urlencoded",
  39. "Key": self._key,
  40. "Sign": self._sha512(encoded_params),
  41. }
  42. conn = http.client.HTTPSConnection(self.API_URL, timeout=self._timeout)
  43. conn.request("POST", f"/{self.API_VERSION}/{name}/", encoded_params, headers)
  44. response = Dict(json.loads(conn.getresponse().read().decode("utf-8")))
  45. conn.close()
  46. if response.result is False:
  47. raise ApiError(params, response)
  48. return response
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement