1
0

utils.py 1.1 KB

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