【问题标题】:How do I connect to my database without hard coding it in flask如何在不在烧瓶中硬编码的情况下连接到我的数据库
【发布时间】:2018-07-23 08:36:19
【问题描述】:

我目前正在通过配置文件中的硬编码链接连接到我的数据库,但我希望能够动态生成此连接,以便将来能够使用多个连接。

SQLALCHEMY_DATABASE_URI = ‘postgresql+psycopg2://<blah>/database’

【问题讨论】:

标签: python flask flask-sqlalchemy


【解决方案1】:

您可以将数据库连接参数放在外部文件中,例如connections_settings.ini

[credentials]
host=localhost
dbname=test
username=me
password=secret

然后使用configparser模块读取它们,并使用字符串插值创建连接url

import configparser
config = configparser.ConfigParser('connection_settings')['credentials']

connection_settings = {
    'host': config['host'],
    'dbname': config['dbname'],
    'user': config['username'],
    'password': config['password']
}

SQLALCHEMY_DATABASE_URI = f'postgresql+psycopg2://{host}/{dbname}'

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2015-09-06
    • 2019-05-07
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多