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.
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 :)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With