fastapi: alembic.ini,url中包含@等特殊字符

一,问题:

密码中包含 @ 时,sqlalchemy.url 必须对密码做 URL 百分号编码(Percent-Encoding):把 @ 编码成 %40。

因为标准数据库连接串格式是:

dialect+driver://username:password@host:port/database

SQLAlchemy 解析时默认以最后一个 @ 作为 userinfo(username:password)与 host 的分隔符;
若密码里带有特殊字符(如 @、#、?、/、:、% 等),直接写进去会导致 URL 解析错乱或认证失败。

二,解决:

在 alembic.ini 中把 @ 写成 %40

假设用户名为 app_user,密码为 P@ss1234,主机为 127.0.0.1:3306,库名为 app_db:

# alembic.ini
sqlalchemy.url = mysql+pymysql://app_user:P%40ss1234@127.0.0.1:3306/app_db

常见特殊字符对照:

  • @ -> %40

  • : -> %3A

  • / -> %2F

  • ? -> %3F

  • # -> %23

  • % -> %25

三,如果还有configparser.InterpolationSyntaxError:报错:

报错信息:

File "/usr/local/soft/python3.14.7/lib/python3.14/configparser.py", line 480, in _interpolate_some
    raise InterpolationSyntaxError(
    ...<2 lines>...
        "found: %r" % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%40@localhost:3306/base' 

根因是 Python 的 configparser 在读取 alembic.ini 时,会把单独的 % 当作插值语法处理;
你把 @ 改成 %40 后,紧跟在 % 后面的 40 不是 % 或 (,因此抛出了 InterpolationSyntaxError。

解决方法:在 alembic.ini 中把 % 转义为 %%

把 %40 写成 %%40(如果密码里还有其他 %xx 编码,也都把 % 写成 %%):

# alembic.ini
sqlalchemy.url = mysql+pymysql://user:pass%%40@localhost:3306/base

验证方式:运行 alembic current 或 alembic heads,
不再报 configparser.InterpolationSyntaxError 即说明 alembic.ini 解析通过。

posted @ 2026-11-19 13:14  刘宏缔的架构森林  阅读(6)  评论(0)    收藏  举报