【问题标题】:using .env variables when configuring env.py file in alembic在 alembic 中配置 env.py 文件时使用 .env 变量
【发布时间】:2022-01-18 15:55:34
【问题描述】:

根据我看到的帖子,这是将 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)

当值只是一个硬编码字符串时,这对我有用。 但是,当我尝试用来自我的 .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)

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

【问题讨论】:

    标签: python sqlalchemy alembic


    【解决方案1】:

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

    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    
    username = os.environ.get("USERNAME")
    password = os.environ.get("PASSWORD")
    

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

    【讨论】:

    • 对,所以我错过了 load_dotenv() 脚本。这已经为我解决了。谢谢!
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 2018-07-14
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多