问题描述
我使用SQLalchemy作为一个Python项目,我想有一个整洁的连接字符串来访问我的数据库。例如:
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?
推荐答案
反斜杠不是URL组件字符串的有效转义字符。您需要对连接字符串的密码部分进行URL编码:
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'))
如果你看一下在SQLAlchemy中使用的类的实现来表示数据库连接URL(在 sqlalchemy / engine / url.py
),您可以看到,当将URL实例转换为字符串时,它们使用相同的方法来转义密码,并且解析代码使用互补的 urllib.unquote_plus
函数从连接字符串中提取密码。
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.
这篇关于当密码包含特殊字符时写入连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!