how to parse mysql database name from database_url

10.3k views Asked by At

DATABASE_URL- MYSQL://username:password@host:port/database_name

Error: database_name has no attributes.

if 'DATABASE_URL' in os.environ:
  url = urlparse(os.getenv['DATABASE_URL'])
 g['db'] = mysql.connector.connect(user=url.username,password=url.password, host=url.hostname ,port=url.port,path=url.path[1:])
4

There are 4 answers

2
alecxe On BEST ANSWER

First of all, url.host would result into:

AttributeError: 'ParseResult' object has no attribute 'host'

use url.hostname instead.

To get the database_name out of the provided URL, use path:

url.path[1:]

An alternative "Don't reinvent the wheel" way to approach the problem would be to use sqlalachemy's make_url(), which is regexp-based:

In [1]: from sqlalchemy.engine.url import make_url

In [2]: url = make_url("MYSQL://username:password@host:100/database_name")

In [3]: print url.username, url.password, url.host, url.port, url.database
username password host 100 database_name
0
guri On

changing path to 'database':url.path[1:] worked for me.

0
Ershan On

update 2022/11/16

Python 3.10.6 (main, Aug 11 2022, 13:47:18) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy.engine.url import make_url
>>> url = make_url("mysql+pymysql://username:password@host:3306/database_name?charset=utf8")
>>> print(url.get_backend_name(),
...       url.get_driver_name(),
...       url.username,
...       url.password,
...       url.host,
...       url.port,
...       url.database,
...       url.query)
mysql pymysql username password host 3306 database_name immutabledict({'charset': 'utf8'})
>>>
0
Putna On

Using standard python3 lib

from urllib.parse import urlparse

dbc = urlparse('mysql://username:password@host:3306/database_name')
print(dbc.scheme, dbc.hostname, dbc.port, dbc.username, dbc.password, dbc.path.lstrip('/'))
#output: mysql host port username password database_name