SqlAlchemy连接字符串 [英] SqlAlchemy connection string
问题描述
我遇到了一个非常奇怪的问题-我使用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?
此问题/答案可能是该问题的重复,因此值得首先检查此 SQLAlchemy文档
the string format of the URL is an RFC-1738-style string.
根据 RFC-1738定义
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编码,以确保正确转义任何此类字符.根据如何在python中对查询字符串进行ur ,这可以在python中使用urlencode()
>
I faced very strange issue - my solution using sqlalchemy cannot connects to database. It depends on password I am using. for example, following records are working perfect:
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)
But when I trying to put something serious to password (like '8yq+aB&k$V
') connection failed. How to 'escape' or encode password somehow that sqlalchemy passed it to mysql succesfully?
This question/answer is perhaps a duplicate of this one so worth checking this first Writing a connection string when password contains special characters
According to the SQLAlchemy documentation
the string format of the URL is an RFC-1738-style string.
According to the 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.
To this end, I would assume that your password (and username for that matter) needs to be URL encoded to ensure any such characters are properly escaped. According to How to urlencode a querystring in Python? this can be done in python using urlencode()
这篇关于SqlAlchemy连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!