【问题标题】:Is there a way to get the connection string out of sqlalchemy in log suitable format?有没有办法以日志合适的格式从 sqlalchemy 中获取连接字符串?
【发布时间】:2017-03-20 15:50:09
【问题描述】:

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

有没有办法从 SQLAlchemy 中解决这个问题,或者我应该求助于正则表达式解析? SQLAlchemy 应该已经对其进行了解析以找出这一点,所以我自己做这件事似乎很愚蠢,但我在 http://docs.sqlalchemy.org/en/latest/core/connections.htmlhttp://docs.sqlalchemy.org/en/latest/core/engines.html 上找不到任何东西

谢谢!

【问题讨论】:

    标签: python database sqlalchemy


    【解决方案1】:

    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__ 中的字符串。

    【讨论】:

      【解决方案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是唯一的补充)

      【讨论】:

      • 最好发表评论或提出修改建议以修复我的答案中的错误。
      猜你喜欢
      • 2020-05-14
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 2015-11-10
      相关资源
      最近更新 更多