Python 3.10.6 alembic postgresql 密码带有特殊字符

问题描述 投票:0回答:2

migrations/env.py

f = open("/etc/config.json", "r")
json_config = json.load(f)
config = context.config
section = config.config_ini_section
print(f"password: {json_config['DB_PASSWORD']}, host: {json_config['DB_HOST']}, db: {json_config['DB_DATABASE']}")
config.set_section_option(section, "DB_USERNAME", json_config["DB_USERNAME"])
config.set_section_option(section, "DB_PASSWORD", urllib.parse.quote_plus(json_config["DB_PASSWORD"]))
config.set_section_option(section, "DB_HOST", json_config["DB_HOST"])
config.set_section_option(section, "DB_DATABASE", json_config["DB_DATABASE"])

alembic.ini

sqlalchemy.url = postgresql://%(DB_USERNAME)s:%(DB_PASSWORD)s@%(DB_HOST)s/%(DB_DATABASE)s

我的密码字符串中有

@
$
。 运行
pipenv run alembic revision --autogenerate -m "Initial migration"
会遇到以下错误:

ValueError: invalid interpolation syntax in 'P%40%24%24w0rd' at position 1
python-3.x postgresql connection-string urllib alembic
2个回答
6
投票

参见 Alembic.ini 密码也需要加倍百分号,解决方案似乎是:

urllib.parse.quote_plus("P@$$w0rd").replace("%", "%%")

为了转义编码的

%
(如
%%
),以便当 Alembic 使用
configparser
解析文件时,它们会得到正确处理。


0
投票

您还可以使用

sqlalchemy.engine.URL
直接在 env.py 中创建 url:

url = URL.create(
    drivername=secrets["drivername"],
    username=secrets["username"],
    password=secrets["password"],
    host=secrets["host"],
    port=secrets["port"],
    database=secrets["database"],
)

然后将这个创建的 URL 传递给 alembic 上下文:

context.configure(
    url=url,
)

这将处理所有需要的转义。

© www.soinside.com 2019 - 2024. All rights reserved.