Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the connection string out of sqlalchemy in log suitable format?

I want to log the database connection, but don't want to show the password (or the driver/dialect).

Is there a way to get this out of SQLAlchemy or should I just resort to regex parsing? SQLAlchemy should have already parsed it to find this out so it seems silly to do it myself, but I can't find anything on http://docs.sqlalchemy.org/en/latest/core/connections.html or http://docs.sqlalchemy.org/en/latest/core/engines.html

Thanks!

like image 549
danio Avatar asked Nov 07 '16 10:11

danio


2 Answers

The URL.__repr__ method hides the password:

from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost/test')

assert repr(engine.url) == 'postgresql://scott:***@localhost/test'

If you want to hide the driver/dialect, you may wish to look at how the URL class computes a string in URL.__to_string__.

like image 158
RazerM Avatar answered Nov 15 '22 08:11

RazerM


Using repr(engine) will include the class name. To get just the URL representation do:

from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost/test')

assert repr(engine.url) == 'postgresql://scott:***@localhost/test'

(note that .url is the only addition)

like image 24
Søren V. Poulsen Avatar answered Nov 15 '22 06:11

Søren V. Poulsen