Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

utils.py 891B

12345678910111213141516171819202122232425262728293031323334353637
  1. import threading
  2. from django.db import connection
  3. from six.moves import queue
  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]