Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a URI in Python?

Tags:

python

uri

I'm trying to convert a Java program to Python, and one thing that I am currently stuck on is working with URI's in Python. I found urllib.response in Python, but I'm struggling to figure out how to utilize it.

What I'm trying to do with this URI is obtain user info (particularly username and password), the host and path. In Java, there are associated methods (getUserInfo(), getHost(), and getPath()) for this, but I'm having trouble finding equivalents for this in Python, even after looking up the urllib.response Python documentation.

The equivalent code in Java is:

URI dbUri = new URI(env);
username = dbUri.getUserInfo().split(":")[0];
password = dbUri.getUserInfo().split(":")[1];
dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();   

and what would be the appropriate methods that could be used to convert this to Python?

like image 849
Daveguy Avatar asked May 22 '26 08:05

Daveguy


1 Answers

Seems like you'd want to use something like urllib.parse.urlparse.

https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse

from urllib.parse import urlparse

db_url = urlparse(raw_url_string)

username = db_url.username
password = db_url.password
host = db_url.net_loc
path = db_url.path
...

You might need to adjust this a bit. There is a subtle difference between urlparse and urlsplit regarding parameters. Then you can use one of the urlunparse or unsplit.

like image 193
Ian Wilson Avatar answered May 23 '26 22:05

Ian Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!