18

I begin a program by generating a URL object and passing it to create_engine. In a section of code far, far away I would like to find out what this engine is connected to, i.e. the connection URL.

Is there an easy way to do this? Using inspect I can only see how to get the driver type. I can understand if the password component of a connection string was no longer available, but I'm hoping everything else is still available.

Any ideas?

4
  • 1
    engine.url returns a URL object Commented Jul 28, 2016 at 9:35
  • Can you be a bit more specific? Your comment looks like you're referring to the module sqlalchemy.engine.url. As far as I can see, the Engine class (sqlalchemy.engine.Engine) has no property documented named url. The only thing I can see how to do is create an object when you already know the details of the connection. I'm trying to work out how to get that information back from an Engine instance. Commented Jul 28, 2016 at 18:39
  • Engine class has a url attribute (github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/engine/…) Looks like it's not documented Commented Jul 28, 2016 at 19:12
  • Ah ha! I hadn't thought something so useful wouldn't be documented. Thank you. Commented Jul 28, 2016 at 19:21

3 Answers 3

9

This works quite well for me:

    log.info("* Using DB: %s" % (engine.url))
Sign up to request clarification or add additional context in comments.

1 Comment

I do not recommend passing raw url to logs. It contains database credentials...
9

The Engine class has an attribute url. Although not documented, it is not 'underscore hidden' so I would assume safe to read.

1 Comment

By default, the __str__/__repr__ representation of engine.url will mask the password like 'postgresql://myuser:***@localhost/test'. If you need the full unmasked string without the password hidden, you should use engine.url.render_as_string(hide_password=False) (docs.sqlalchemy.org/en/20/core/…)
1

Docs have improved over time: https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.engine.URL

The database url (dialect+driver://username:password@host:port/database) can be viewed as a string via render_as_string(hide_password: bool = True), which also gives you control over whether or not to show the password in plain text. By default, the class' __repr__ calls return self.render_as_string(), so will mask out the password.

And if you wanted the dialect or its components, you can call get_dialect, get_backend_name i.e. the lhs of the +, and get_driver_name i.e. the rhs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.