【问题标题】:How can I change the Flask-SQLAlchemy URI after a certain period of time?一段时间后如何更改 Flask-SQLAlchemy URI?
【发布时间】:2019-04-25 22:55:13
【问题描述】:

我正在使用 Flask-SQLAlchemy 连接到 AWS RDS 上的 Postgres 数据库。连接数据库的密码每 15 分钟过期一次,之后我需要为新的数据库连接生成一个新密码(打开连接即可)。

我不知道如何配置 Flask-SQLAlchemy 以使用函数来生成 SQLALCHEMY_DATABASE_URI 配置参数。围绕这一点的所有文档和讨论都指向在启动时使用静态值集。

我知道如何使用常规 SQLAlchemy 和范围会话等来做到这一点。但我真的希望能找到使用 Flask-SQLALchemy 的解决方案。

【问题讨论】:

  • 您尝试使用Custom Connection Function 还是engine_connect listen?看起来像你需要的。
  • @DanilaGanchar,是的,我认为自定义连接函数会起作用,尽管仅在两天前的 Flask-SQLAlchemy 版本中起作用,这是非常幸运的。

标签: python postgresql flask flask-sqlalchemy rds


【解决方案1】:

为了完整起见,我使用 @DanilaGanchar 建议的 custom connection function 来完成这项工作。

要在 Flask-SQLAlchemy 中进行配置,您需要使用 v2.4.0 或更高版本(顺便说一下,只有 released the day before I asked this question)。该版本有一个 SQLALCHEMY_ENGINE_OPTIONS 配置,它允许为 SQLAlchemy 的 create_engine 函数传入一个 kwargs 字典。

一个重要的注意事项是 Flask-SQLAlchemy 仍然需要 SQLALCHEMY_DATABASE_URI 的值,即使您的 creator 函数正在处理创建连接。

所以完整的解决方案看起来像

# config.py

def _get_conection():
    # Get all your connection information
    return psycopg2.connect(host=host, port=5432, password=password, ...

SQLALCHEMY_DATABASE_URI = "postgresql+pyscopg2://"
SQLALCHEMY_ENGINE_OPTIONS = {"creator": _get_connection}
# More settings etc.
# app.py

from app import config
from app.db import db

def create_app():
    app = Flask(__name__)
    app.config_from_object(config)
    db.init_app(app)
    return app

【讨论】:

  • {"creator": _get_connection()} 应该是 {"creator": _get_connection}
猜你喜欢
  • 1970-01-01
  • 2019-12-31
  • 2012-11-08
  • 2011-06-16
  • 2017-08-04
  • 2019-12-09
  • 2013-01-07
  • 2018-05-18
  • 1970-01-01
相关资源
最近更新 更多