根据我看到的帖子,这是将alembic.ini sqlalchemy.url指向alembic env.py文件中所需的db路径的最常见方法
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)
当值只是一个硬编码字符串时,这对我来说是有效的。但是,当我试图用来自我的.env文件的隐藏变量替换用户名和密码值时,我总是收到一个操作错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: role "None" does not exist
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)
我做错了什么,不允许我使用我的环境变量?
发布于 2022-01-18 07:55:34
我建议使用多滕诺夫 (pip install python-dotenv
)如下:
import os
from dotenv import load_dotenv
load_dotenv()
username = os.environ.get("USERNAME")
password = os.environ.get("PASSWORD")
(dotenv没有任何外部库依赖项,这很好)
https://stackoverflow.com/questions/70750753
复制相似问题