我有一个基于简单教程的简单 Flask 应用程序,我正在尝试将我的数据库凭据从代码中取出并放入环境变量中。我在
DB_CONNECTION_STR
中定义了 .env
,它位于我的应用程序的根目录中。以下是我的 database.py
文件的顶部。这应该是一个简单的修复;我可能遗漏了一个明显的错字。
from sqlalchemy import create_engine, text
import os
DB_CONNECTION_STR = os.environ.get('DB_CONNECTION_STR')
# These both print the right value:
print(DB_CONNECTION_STR)
print(os.environ.get('DB_CONNECTION_STR'))
# This works:
db_connection_string = "mysql+pymysql://ehcazu8mvtvv4i44ghs3:pscale_pw_i960dmnsHwOCf3IWmKZi4AzOMVi1ZueGLYRiPZAy3i9@aws.connect.psdb.cloud/joviancareers?charset=utf8mb4"
# Trying either of these two gives me a "AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'"
# db_connection_string = DB_CONNECTION_STR
# db_connection_string = os.environ.get('DB_CONNECTION_STR')
engine = create_engine(db_connection_string, connect_args={
"ssl": {
"ca": "/etc/ssl/certs/ca-certificates.crt"
}
})
这是我收到的错误:
Traceback (most recent call last):
File "/home/taylor/src/jovian-carrers/app.py", line 2, in <module>
from database import load_jobs
File "/home/taylor/src/jovian-carrers/database.py", line 17, in <module>
engine = create_engine(db_connection_string,
File "<string>", line 2, in create_engine
File "/home/taylor/src/jovian-carrers/venv/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs)
File "/home/taylor/src/jovian-carrers/venv/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 518, in create_engine
u, plugins, kwargs = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
在我的头撞在墙上一个小时后,我在发布问题后立即弄清楚了。我必须将代码放置在函数内部来设置引擎,并且我假设当它位于函数外部时,它在应用程序编译时无法访问环境变量?
这不起作用:
DB_CONNECTION_STR = os.environ.get('DB_CONNECTION_STR')
db_connection_string = DB_CONNECTION_STR
engine = create_engine(db_connection_string, connect_args = {
"ssl": {
"ca": "/etc/ssl/certs/ca-certificates.crt"
}
})
def load_jobs():
with engine.connect() as conn:
result = conn.execute(text("SELECT * FROM jobs"))
jobs = [dict(row) for row in result.all()]
return jobs
这可行,但需要硬编码凭据:
db_connection_string = "mysql+pymysql://ehcazu8mvtvv4i44ghs3:pscale_pw_i960dmnsHwOCf3IWmKZi4AzOMVi1ZueGLYRiPZAy3i9@aws.connect.psdb.cloud/joviancareers?charset=utf8mb4"
engine = create_engine(db_connection_string, connect_args = {
"ssl": {
"ca": "/etc/ssl/certs/ca-certificates.crt"
}
})
def load_jobs():
with engine.connect() as conn:
result = conn.execute(text("SELECT * FROM jobs"))
jobs = [dict(row) for row in result.all()]
return jobs
这无需硬编码凭据即可工作:
def load_jobs():
DB_CONNECTION_STR = os.environ.get('DB_CONNECTION_STR')
db_connection_string = DB_CONNECTION_STR
engine = create_engine(db_connection_string, connect_args = {
"ssl": {
"ca": "/etc/ssl/certs/ca-certificates.crt"
}
})
with engine.connect() as conn:
result = conn.execute(text("SELECT * FROM jobs"))
jobs = [dict(row) for row in result.all()]
return jobs