且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当密码包含特殊字符时写入连接字符串

更新时间:2023-02-26 10:59:05

反斜杠不是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.