SqlAlchemy连接字符串

时间:2013-07-22 12:00:20

标签: python mysql sqlalchemy

我遇到了一个非常奇怪的问题 - 我使用sqlalchemy的解决方案无法连接到数据库。这取决于我使用的密码。例如,以下记录工作正常:

PWD='123123123'
USR='test_user';
SQLALCHEMY_DATABASE_URI = 'mysql://{}:{}@localhost:3306/test_db'.format(USR, PWD)

#final result is 'mysql://test_user:123123123@localhost:3306/test_db'.format(USR, PWD)

但是,当我尝试将严重的内容置于密码(例如“8yq+aB&k$V”)连接失败时。如何以某种方式“转义”或编码密码sqlalchemy成功地将其传递给mysql?

1 个答案:

答案 0 :(得分:10)

这个问题/答案可能与此问题重复,因此值得首先查看Writing a connection string when password contains special characters

根据SQLAlchemy documentation

the string format of the URL is an RFC-1738-style string.

根据RFC-1738 definition

If the character corresponding to an octet is
reserved in a scheme, the octet must be encoded.  The characters ";",
"/", "?", ":", "@", "=" and "&" are the characters which may be
 reserved for special meaning within a scheme.

为此,我假设您的密码(以及该用户的用户名)需要进行URL编码,以确保正确转义任何此类字符。根据{{​​3}},这可以使用urlencode()

在python中完成