You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utilities.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # utilities.py
  2. # ~~~~~~~~~
  3. # This module implements the utility methods.
  4. # :authors: Justin Karneges, Konstantin Bokarius.
  5. # :copyright: (c) 2015 by Fanout, Inc.
  6. # :license: MIT, see LICENSE for more details.
  7. import sys
  8. import collections
  9. import jwt
  10. import calendar
  11. import copy
  12. from datetime import datetime
  13. try:
  14. import zmq
  15. except ImportError:
  16. zmq = None
  17. try:
  18. import tnetstring
  19. except ImportError:
  20. tnetstring = None
  21. is_python3 = sys.version_info >= (3,)
  22. # An internal method to verify that the zmq and tnetstring packages are
  23. # available. If not an exception is raised.
  24. def _verify_zmq():
  25. if zmq is None:
  26. raise ValueError('zmq package must be installed')
  27. if tnetstring is None:
  28. raise ValueError('tnetstring package must be installed')
  29. # An internal method for encoding the specified value as UTF8 only
  30. # if it is unicode. This method acts recursively and will process nested
  31. # lists and dicts.
  32. def _ensure_utf8(value):
  33. if is_python3:
  34. if isinstance(value, str):
  35. return value.encode('utf-8')
  36. else:
  37. if isinstance(value, unicode):
  38. return value.encode('utf-8')
  39. elif isinstance(value, str):
  40. return value
  41. if isinstance(value, collections.Mapping):
  42. return dict(map(_ensure_utf8, value.items()))
  43. elif isinstance(value, collections.Iterable):
  44. return type(value)(map(_ensure_utf8, value))
  45. return value
  46. # An internal method for decoding the specified value as UTF8 only
  47. # if it is binary. This method acts recursively and will process nested
  48. # lists and dicts.
  49. def _ensure_unicode(value):
  50. if is_python3:
  51. if isinstance(value, bytes):
  52. return value.decode('utf-8')
  53. if isinstance(value, str):
  54. return value
  55. else:
  56. if isinstance(value, str):
  57. return value.decode('utf-8')
  58. elif isinstance(value, unicode):
  59. return value
  60. if isinstance(value, collections.Mapping):
  61. return dict(map(_ensure_unicode, value.items()))
  62. elif isinstance(value, collections.Iterable):
  63. return type(value)(map(_ensure_unicode, value))
  64. return value
  65. # An internal method for generating a JWT authorization header based on
  66. # the specified claim and key.
  67. def _gen_auth_jwt_header(claim, key):
  68. if 'exp' not in claim:
  69. claim = copy.copy(claim)
  70. claim['exp'] = calendar.timegm(datetime.utcnow().utctimetuple()) + 3600
  71. else:
  72. claim = claim
  73. return 'Bearer ' + jwt.encode(claim, key).decode('utf-8')