1
0

utils.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import random
  2. import socket
  3. import string
  4. from collections import OrderedDict
  5. from contextlib import closing
  6. def get_free_port():
  7. """
  8. pick a free port number
  9. :return int: port number
  10. """
  11. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  12. s.bind(('', 0))
  13. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  14. return s.getsockname()[1]
  15. def random_str(len=16):
  16. """生成小写字母和数组组成的随机字符串
  17. :param int len: 字符串长度
  18. """
  19. return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(len))
  20. def run_as_function(gen):
  21. res = None
  22. while 1:
  23. try:
  24. res = gen.send(res)
  25. except StopIteration as e:
  26. if len(e.args) == 1:
  27. return e.args[0]
  28. return
  29. async def to_coroutine(gen):
  30. res = None
  31. while 1:
  32. try:
  33. c = gen.send(res)
  34. res = await c
  35. except StopIteration as e:
  36. if len(e.args) == 1:
  37. return e.args[0]
  38. return
  39. class LRUDict(OrderedDict):
  40. """
  41. Store items in the order the keys were last recent updated.
  42. The last recent updated item was in end.
  43. The last furthest updated item was in front.
  44. """
  45. def __setitem__(self, key, value):
  46. OrderedDict.__setitem__(self, key, value)
  47. self.move_to_end(key)