有没有办法以log适当的格式从sqlalchemy中获取连接字符串?

时间:2016-11-07 10:24:15

标签: python database sqlalchemy

我想记录数据库连接,但不想显示密码(或驱动程序/方言)。

有没有办法从SQLAlchemy中解决这个问题,还是应该采用正则表达式解析? SQLAlchemy应该已经解析了它以找到它,所以看起来很愚蠢自己做,但我在http://docs.sqlalchemy.org/en/latest/core/connections.htmlhttp://docs.sqlalchemy.org/en/latest/core/engines.html上找不到任何东西

谢谢!

2 个答案:

答案 0 :(得分:5)

URL.__repr__方法隐藏密码:

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

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

如果您想隐藏驱动程序/方言,您可能希望查看URL类如何计算URL.__to_string__中的字符串。

答案 1 :(得分:2)

使用repr(engine)将包含类名。要仅获取URL表示,请执行以下操作:

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

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

(请注意,.url是唯一的添加项)