11

Given a database connection string structure (such like one you can find here) what's the best way to parse a real URI string and get their component like user, password, database name and host?

Thank you very much

4 Answers 4

17

There is a Python library for that:

Sign up to request clarification or add additional context in comments.

Comments

11

You can use urlparse

Python2:

from urlparse import urlparse

Python3:

from urllib.parse import urlparse

Example:

r = urlparse('mysql://alex:pwd@localhost/test')

print(r.username)
# 'alex'

print(r.password)
# 'pwd'

1 Comment

it works if only you don't have char '#' in password :(
7

A regular expression (depending on the specific syntax)!?

For example:

m = re.match('mysql://(.*?):(.*?)@(.*?)/(.*)', url)

is supposed to give you user, password, host and database in the groups 1 to 4:

print(m.groups())

Or in one line:

user, password, host, database = re.match('mysql://(.*?):(.*?)@(.*?)/(.*)', url).groups()

2 Comments

that case, when accepted answer is not the best one;)
If we string contains database port, it is parsed together with host. For string "mysql://dbaas:[email protected]:3310/my_db", we would have host = 100.81.0.179:3310
5

While urllib.parse provides general URL parsing, SQLAlchemy provides a parser specifically designed for database URLs (aka "connection strings"), providing a handful of useful methods and properties:

from sqlalchemy.engine import make_url, URL

url = make_url("postgres://user:pw@localhost/mydbname")

assert url.host == "localhost"
assert url.username == "user"
assert isinstance(url, URL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.