是的,这是正确的主意。我喜欢基本配置文件的yaml,但是你可以使用任何格式。如果你使用yaml,它会像这样:
-
使用适当的读/写/执行权限在repo外部生成一个yaml文件。
database_info:
username: edamame
password: mypassword
host: 1.2.3.4
port: 3306
database: mydb
-
用PyYAML导入。
import yaml
with open('your/file/path/here/db_config.yaml', 'r') as infile:
db_cfg = yaml.safe_load(infile)
-
访问变量并填充字符串(我通常将其包装在函数中):
engine = create_engine(
'mysql+pymysql://{}:{}@{}:{}/{}'.format(
db_cfg['database_info']['username'],
db_cfg['database_info']['mypassword'],
db_cfg['database_info']['host'],
db_cfg['database_info']['port'],
db_cfg['database_info']['database']
)
)
确保配置文件不在repo中,并且目录/文件权限正确。如果您正在构建一个web应用程序,另一个好的选择是环境变量。您可以使用Python的os库访问它们。