Writing a connection string when password contains special characters

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.

Leave a Comment