Skip to content

Instantly share code, notes, and snippets.

@AstraLuma
Last active May 13, 2021 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AstraLuma/00e511feb1f619f407d07e968d69f36b to your computer and use it in GitHub Desktop.
Save AstraLuma/00e511feb1f619f407d07e968d69f36b to your computer and use it in GitHub Desktop.
def mutate_url(url, *,
username=None, password=None, hostname=None, port=None, **kwargs
):
import urllib.parse
bits = urllib.parse.urlparse(url)
assert not ( (username or password or hostname or port) and 'netloc' in kwargs ) # noqa
if username or password or hostname or port:
# FIXME: url encoding
u = username or bits.username
w = password or bits.password
h = hostname or bits.hostname
p = port or bits.port
if u or p:
userinfo = f"{u}:{w}@"
else:
userinfo = ""
if port:
kwargs['netloc'] = f"{userinfo}{h}:{p}"
else:
kwargs['netloc'] = f"{userinfo}{h}"
newbits = bits._replace(**kwargs)
return newbits.geturl()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment