'Database connection string parsing in python

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



Solution 1:[1]

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()

Solution 2:[2]

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'

Solution 3:[3]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robin Koch
Solution 2
Solution 3 Stew