我正在使用SQLalchemy作为Python项目,我希望有一个整洁的连接字符串来访问我的数据库。例如:
engine = create_engine('postgres://user:pass@host/database')
问题是我的密码包含一系列特殊字符,在我尝试连接时会被解释为分隔符。
我意识到我可以创建一个对象然后传递我的凭据:
drivername = 'postgres',
username = 'user',
password = 'pass',
host = 'host',
database = 'database'
但如果可行,我宁愿使用连接字符串。
所以要清楚,是否可以对连接字符串或连接字符串的密码部分进行编码,以便正确解析?
答案 0 :(得分:46)
反斜杠不是URL组件字符串的有效转义字符。您需要对连接字符串的密码部分进行URL编码:
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
函数从连接字符串中提取密码。
答案 1 :(得分:2)
在 Python 3.x 中,需要导入 urllib.parse.quote:
<块引用>urllib 模块在 Python 3 中被拆分为多个部分并重命名为 urllib.request、urllib.parse 和 urllib.error。
当您尝试使用包含特殊字符序列的密码连接数据库 MySQL 并且您的 Python 版本是 Python3 时
user_name 是您的数据库用户 ID
数据库是您的数据库名称
your_password 带有特殊字符的密码
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'))