how to parse mysql database name from database_url
Asked Answered
R

4

15

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:])
Rodrigo answered 24/6, 2015 at 20:31 Comment(0)
S
28

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
Suzette answered 24/6, 2015 at 20:40 Comment(2)
I changed my code: g['db'] = mysql.connector.connect(user=url.username,password=url.password, host=url.hostname ,port=url.port,path=url.path[1:]) but it is it is now giving me error:errorraise AttributeError("Unsupported argument '{0}'".format(key)) app[stderr.0]: AttributeError: Unsupported argument 'path'Rodrigo
Use url.drivername for the drivername attribute ("mysql" in this case)Puberty
E
15

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
Edwyna answered 4/4, 2020 at 20:21 Comment(0)
R
1

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

Rodrigo answered 24/6, 2015 at 21:48 Comment(0)
S
-1

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'})
>>>
Scorcher answered 16/11, 2022 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.