utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # coding: utf-8
  2. import json
  3. import hashlib
  4. import asyncio
  5. @asyncio.coroutine
  6. def generate_key(app, queue):
  7. return '{}-{}'.format(app, queue)
  8. @asyncio.coroutine
  9. def request_to_dict(request_):
  10. try:
  11. data = yield from request_.json()
  12. except:
  13. data = yield from request_.text()
  14. header = dict(request_.headers)
  15. return {
  16. 'method': request_.method,
  17. 'header': header,
  18. 'data': data,
  19. }
  20. @asyncio.coroutine
  21. def encode_json(data):
  22. return json.dumps(data).encode('latin-1')
  23. def decode_json(data):
  24. if data:
  25. return json.loads(data.decode('latin-1'))
  26. else:
  27. return dict()
  28. @asyncio.coroutine
  29. def normalize_path(path):
  30. """ Normalize path
  31. Removes double slash from path
  32. """
  33. path = '/'.join([split for split in path.split('/') if split != ''])
  34. if not path.startswith('/'):
  35. path = '/{}'.format(path)
  36. if not path.endswith('/'):
  37. path = '{}/'.format(path)
  38. return path
  39. @asyncio.coroutine
  40. def hash_dict(dictionary):
  41. json_data = json.dumps(dictionary, sort_keys=True).encode('utf-8')
  42. return hashlib.sha1(json_data).hexdigest()
  43. def compare_hash(expected_hash, received_hash):
  44. return expected_hash == received_hash