在 alembic 中配置 env.py 文件时使用 .env 变量

Ben*_*Ten 2 python sqlalchemy alembic

根据我看到的帖子,这是将 alembic.ini sqlalchemy.url 指向 alembic env.py 文件中所需的数据库路径的最常见方法

import os

from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.

connection_string = f'postgresql+psycopg2://<username>:<password>@localhost/test_server'

config = context.config
config.set_main_option('sqlalchemy.url', connection_string)
Run Code Online (Sandbox Code Playgroud)

当该值只是一个硬编码字符串时,这对我有用。但是,当我尝试用来自 .env 文件的隐藏变量替换用户名和密码值时,我总是收到操作错误:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:  role "None" does not exist
Run Code Online (Sandbox Code Playgroud)
username = os.environ.get("USERNAME")
password = os.environ.get("PASSWORD")

connection_string = f'postgresql+psycopg2://{username}:{password}@localhost/test_server'

config = context.config
config.set_main_option('sqlalchemy.url', connection_string)
Run Code Online (Sandbox Code Playgroud)

我做错了什么不允许我使用我的环境变量?

小智 7

我建议像这样使用dotenv ( ) :pip install python-dotenv

import os
from dotenv import load_dotenv

load_dotenv()

username = os.environ.get("USERNAME")
password = os.environ.get("PASSWORD")
Run Code Online (Sandbox Code Playgroud)

(dotenv 没有任何外部库依赖项,这很好)