如何在不对烧瓶进行硬编码的情况下连接到数据库

时间:2018-07-23 08:36:19

标签: python flask flask-sqlalchemy

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

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

1 个答案:

答案 0 :(得分:0)

您可以将数据库连接参数放在一个外部文件中,例如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}'
相关问题