utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # coding: utf-8
  2. import json
  3. import socket
  4. import hashlib
  5. import asyncio
  6. from contextlib import closing
  7. @asyncio.coroutine
  8. def generate_key(app, queue):
  9. return '{}-{}'.format(app, queue)
  10. @asyncio.coroutine
  11. def request_to_dict(request):
  12. try:
  13. data = yield from request.json()
  14. except:
  15. data = yield from request.text()
  16. header = dict(request.headers)
  17. return {
  18. 'method': request.method,
  19. 'header': header,
  20. 'data': data,
  21. }
  22. @asyncio.coroutine
  23. def encode_json(data):
  24. return json.dumps(data)
  25. def decode_json(data):
  26. if data:
  27. return json.loads(data)
  28. else:
  29. return dict()
  30. # TODO: Changes to use https://github.com/rbaier/python-urltools/
  31. # do not forget PUBLIC_SUFFIX_LIST env var!
  32. @asyncio.coroutine
  33. def normalize_path(path):
  34. """ Normalize path
  35. Removes double slash from path
  36. """
  37. path = '/'.join([split for split in path.split('/') if split != ''])
  38. if not path.startswith('/'):
  39. path = '/{}'.format(path)
  40. if not path.endswith('/'):
  41. path = '{}/'.format(path)
  42. return path
  43. @asyncio.coroutine
  44. def hash_dict(dictionary):
  45. json_data = json.dumps(dictionary, sort_keys=True).encode('utf-8')
  46. return hashlib.sha1(json_data).hexdigest()
  47. def compare_hash(expected_hash, received_hash):
  48. return expected_hash == received_hash
  49. def unused_tcp_port():
  50. """ Unused tcp port
  51. Find an unused localhost TCP port from 1024-65535 and return it.
  52. From:
  53. github.com/pytest-dev/pytest-asyncio/blob/master/pytest_asyncio/plugin.py
  54. See it own LICENSE file for details
  55. """
  56. with closing(socket.socket()) as sock:
  57. sock.bind(('127.0.0.1', 0))
  58. return sock.getsockname()[1]
  59. def make_server(protocol):
  60. from .protocol import HTTPProxy
  61. return HTTPProxy