fork download
  1. import re
  2. import urllib.parse
  3.  
  4. def url_replace_hostname(url_parse_result, hostname):
  5. userinfo, sep, hostinfo = url_parse_result.netloc.rpartition('@')
  6. if ':' in hostname:
  7. hostname = f'[{hostname}]'
  8. return url_parse_result._replace(netloc=userinfo + sep +
  9. re.subn(r'\[[^]]*]|[^:]+', hostname, hostinfo, 1)[0])
  10.  
  11. for url, hostname in (
  12. ('https://127.0.0.1:6443', 'foo'),
  13. ('http://u...content-available-to-author-only...r.pass@bar', '1.2.3.4'),
  14. ('http://user:pass@80:80', '1111:1111:1111:1111:1111'),
  15. ('http://[fe80::822a:a8ff:fe49:470c%tESt]:1234', 'baz.com')
  16. ):
  17. print(url_replace_hostname(urllib.parse.urlparse(url), hostname).geturl())
Success #stdin #stdout 0.04s 9768KB
stdin
Standard input is empty
stdout
https://foo:6443
http://u...content-available-to-author-only...r.pass@1.2.3.4
http://user:pass@[1111:1111:1111:1111:1111]:80
http://b...content-available-to-author-only...z.com:1234