hosts.py 748 B

1234567891011121314151617181920212223242526
  1. import random
  2. try:
  3. from urlparse import urlsplit
  4. except ImportError:
  5. # try python3 then
  6. from urllib.parse import urlsplit
  7. def collect_hosts(hosts, randomize=True):
  8. """Collect a set of hosts and an optional chroot from a string."""
  9. host_ports, chroot = hosts.partition("/")[::2]
  10. chroot = "/" + chroot if chroot else None
  11. result = []
  12. for host_port in host_ports.split(","):
  13. # put all complexity of dealing with
  14. # IPv4 & IPv6 address:port on the urlsplit
  15. res = urlsplit("xxx://" + host_port)
  16. host = res.hostname
  17. port = int(res.port) if res.port else 2181
  18. result.append((host.strip(), port))
  19. if randomize:
  20. random.shuffle(result)
  21. return result, chroot