Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using SQLalchemy for a Python project, and I want to have a tidy connection string to access my database. So for example:

engine = create_engine('postgres://user:pass@host/database')

The problem is my password contains a sequence of special characters that get interpreted as delimiters when I try to connect.

I realize I could just create an object and then pass my credentials like this:

drivername  = 'postgres',
username    = 'user', 
password    = 'pass', 
host        = 'host',
database    = 'database'

But I'd much rather use a connection string if this is possible.

So to be clear, is it possible to encode my connection string, or the password part of the connection string - so that it can be properly parsed?

question from:https://stackoverflow.com/questions/1423804/writing-a-connection-string-when-password-contains-special-characters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
281 views
Welcome To Ask or Share your Answers For Others

1 Answer

Backslashes aren't valid escape characters for URL component strings. You need to URL-encode the password portion of the connect string:

from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engine = create_engine('postgres://user:%s@host/database' % urlquote('badpass'))

If you look at the implementation of the class used in SQLAlchemy to represent database connection URLs (in sqlalchemy/engine/url.py), you can see that they use the same method to escape passwords when converting the URL instances into strings, and that the parsing code uses the complementary urllib.unquote_plus function to extract the password from a connection string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...