utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import hashlib
  2. import socket
  3. from .python_3x import url_encode
  4. # define constants
  5. CONFIGURATIONS = "configurations"
  6. NOTIFICATION_ID = "notificationId"
  7. NAMESPACE_NAME = "namespaceName"
  8. # add timestamps uris and keys
  9. def signature(timestamp, uri, secret):
  10. import base64
  11. import hmac
  12. string_to_sign = "" + timestamp + "\n" + uri
  13. hmac_code = hmac.new(secret.encode(), string_to_sign.encode(), hashlib.sha1).digest()
  14. return base64.b64encode(hmac_code).decode()
  15. def url_encode_wrapper(params):
  16. return url_encode(params)
  17. def no_key_cache_key(namespace, key):
  18. return "{}{}{}".format(namespace, len(namespace), key)
  19. # Returns whether the obtained value is obtained, and None if it does not
  20. def get_value_from_dict(namespace_cache, key):
  21. if namespace_cache:
  22. kv_data = namespace_cache.get(CONFIGURATIONS)
  23. if kv_data is None:
  24. return None
  25. if key in kv_data:
  26. return kv_data[key]
  27. return None
  28. def init_ip():
  29. ip = ""
  30. s = None
  31. try:
  32. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  33. s.connect(("8.8.8.8", 53))
  34. ip = s.getsockname()[0]
  35. finally:
  36. if s:
  37. s.close()
  38. return ip