Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse mysql database name from database_url

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:])
like image 242
guri Avatar asked Jun 24 '15 20:06

guri


1 Answers

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
like image 111
alecxe Avatar answered Oct 30 '22 10:10

alecxe