Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a connection string when password contains special characters

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('postgresql://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 that I could just use engine.URL.create() and then pass my credentials like this:

import sqlalchemy as sa

connection_url = sa.engine.URL.create(
    drivername="postgresql",
    username="user",
    password="p@ss",
    host="host",
    database="database",
)
print(connection_url)
# postgresql://user:p%40ss@host/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?

like image 990
KeyboardInterrupt Avatar asked Sep 14 '09 20:09

KeyboardInterrupt


People also ask

How do you pass a special character with a password in Python?

Simply use \ character before '!' or other special characters. Show activity on this post. Python does not like the special characters.


2 Answers

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.

like image 98
rcoder Avatar answered Sep 20 '22 16:09

rcoder


In Python 3.x, you need to import urllib.parse.quote:

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

When you are trying to connect database MySQL with password which contains sequence of special characters and your python version is Python3

user_name is your userid for database
database is your database name
your_password password with special characters

 from urllib.parse import quote    from sqlalchemy.engine import create_engine  engine = create_engine('mysql+mysqlconnector://user_name:%s@localhost:3306/database' % quote('your_password')) 
like image 37
prdip Avatar answered Sep 21 '22 16:09

prdip