utils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import asyncio
  2. import random
  3. import socket
  4. import string
  5. import time
  6. from collections import OrderedDict
  7. from contextlib import closing
  8. async def wait_host_port(host, port, duration=10, delay=2):
  9. """Repeatedly try if a port on a host is open until duration seconds passed
  10. from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
  11. :param str host: host ip address or hostname
  12. :param int port: port number
  13. :param int/float duration: Optional. Total duration in seconds to wait, by default 10
  14. :param int/float delay: Optional. Delay in seconds between each try, by default 2
  15. :return: awaitable bool
  16. """
  17. tmax = time.time() + duration
  18. while time.time() < tmax:
  19. try:
  20. _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5)
  21. writer.close()
  22. await writer.wait_closed()
  23. return True
  24. except:
  25. if delay:
  26. await asyncio.sleep(delay)
  27. return False
  28. def get_free_port():
  29. """
  30. pick a free port number
  31. :return int: port number
  32. """
  33. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  34. s.bind(('', 0))
  35. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  36. return s.getsockname()[1]
  37. def random_str(len=16):
  38. """生成小写字母和数组组成的随机字符串
  39. :param int len: 字符串长度
  40. """
  41. return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(len))
  42. def run_as_function(gen):
  43. res = None
  44. while 1:
  45. try:
  46. res = gen.send(res)
  47. except StopIteration as e:
  48. if len(e.args) == 1:
  49. return e.args[0]
  50. return
  51. async def to_coroutine(gen):
  52. res = None
  53. while 1:
  54. try:
  55. c = gen.send(res)
  56. res = await c
  57. except StopIteration as e:
  58. if len(e.args) == 1:
  59. return e.args[0]
  60. return
  61. class LRUDict(OrderedDict):
  62. """
  63. Store items in the order the keys were last recent updated.
  64. The last recent updated item was in end.
  65. The last furthest updated item was in front.
  66. """
  67. def __setitem__(self, key, value):
  68. OrderedDict.__setitem__(self, key, value)
  69. self.move_to_end(key)