您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

utils.py 875B

123456789101112131415161718192021222324252627282930313233343536
  1. import queue
  2. import threading
  3. from django.db import connection
  4. def run_concurrently(fn, kwargs=None, num_threads=5):
  5. exceptions = queue.Queue()
  6. def worker(**kwargs):
  7. try:
  8. fn(**kwargs)
  9. except Exception as exc:
  10. exceptions.put(exc)
  11. else:
  12. exceptions.put(None)
  13. finally:
  14. connection.close()
  15. kwargs = kwargs if kwargs is not None else {}
  16. # Run them
  17. threads = [
  18. threading.Thread(target=worker, name='thread-%d' % i, kwargs=kwargs)
  19. for i in range(num_threads)
  20. ]
  21. try:
  22. for thread in threads:
  23. thread.start()
  24. finally:
  25. for thread in threads:
  26. thread.join()
  27. # Retrieve exceptions
  28. exceptions = [exceptions.get(block=False) for i in range(num_threads)]
  29. return [exc for exc in exceptions if exc is not None]