Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use mysql defaults file (my.cnf) with sqlalchemy?

I'd like to have sqlalchemy get the hostname, username, and password for the mysql database it's connecting to.

The documentation says mysql schemas are specified as such:

mysql_db = create_engine('mysql://scott:tiger@localhost/foo')

Is it possible to instead source a mysql defaults file such as /etc/my.cnf and get the login details from there? I'd like to avoid embedding the username/password in my code.

like image 863
Christine Avatar asked Dec 05 '22 23:12

Christine


2 Answers

Here is a result that was found on the sqlalchemy mailing list, posted by Tom H:

http://www.mail-archive.com/[email protected]/msg11241.html

from sqlalchemy.engine.url import URL

myDB = URL(drivername='mysql', host='localhost',
    database='my_database_name',
    query={ 'read_default_file' : '/path/to/.my.cnf' }
)
engine = create_engine(name_or_url=myDB)
# use the engine as usual, no password needed in your code file :)
like image 59
Mark Hildreth Avatar answered Dec 10 '22 11:12

Mark Hildreth


If you want to use MySQLdb you could parse the ini file with ConfigParser:

sql_ini_fileparser = ConfigParser.RawConfigParser()
sql_ini_fileparser.read('example.cfg')
user = sql_ini_fileparser.get('client', 'user')
password = sql_ini_fileparser.get('client', 'password')
like image 41
Karel Avatar answered Dec 10 '22 10:12

Karel