Update/add username in url in python

Viewed 2204

If I have a URL (ex: "ssh://hello@xyz.com:553/random_uri", "https://test.blah.blah:993/random_uri2"), I want to set/update the username in the url. I know there is urllib.parse.urlparse (https://docs.python.org/3/library/urllib.parse.html) that would break them down but I am having trouble creating a new url (or updating) the parsed result with the username I intend to use.

Is there any python library that can help set/update username? Preferably using the parsed result of an urlparse.

2 Answers

Let me to show a script without 3rd package.

from urllib.parse import urlparse

old_url = "https://user:password@search-books-edupractice.es.amazonaws.com"
user="user-01"
password="my-secure-password"

_url = urlparse(old_url)
domain = _url.netloc.split("@")[-1]
new_url = "{}://{}:{}@{}".format(_url.scheme, user,password, domain)

Run the script, the variable new_url contains your url with new user and password.

Related