您使用环境变量的本能是正确的。但是,存在使用错误的数据库运行单元测试的危险。另外,您可能不想在
connect_db每个请求中都想使用任何地方
db。您可以使用配置目录和明确设置的环境变量。这是到目前为止我提出的最好的。
run.pyshell.pyconfig/__init__.pyconfig/test.pyconfig/postgres.py...main/__init__.pymain/someapp/__init__.pymain/someapp/models.py...main/tests/__init__.pymain/tests/testutils.py
因此,配置文件可能是:
# config/test.pySQLALCHEMY_DATAbase_URI = "sqlite://"
和
# config/postgres.pySQLALCHEMY_DATAbase_URI = 'postgresql://user:pw@localhost/somedb'
因此,我可以在基本TestCase中显式设置数据库:
import osfrom flask.ext.testing import TestCaseos.environ["DIAG_CONFIG_MODULE"] = "config.test"from main import app, dbclass SQLAlchemyTest(TestCase): def create_app(self): return app def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all()
然后,
main/__init__.py对我来说:
import osfrom flask import Flask, render_template, gfrom flask.ext.sqlalchemy import SQLAlchemy# by default, let's use a DB we don't care about# but, we can override if we wantconfig_obj = os.environ.get("DIAG_CONFIG_MODULE", "config.test")app = Flask(__name__)app.config.from_object(config_obj)db = SQLAlchemy(app)@app.before_requestdef before_request(): g.db = db g.app = app# ...@app.route('/', methods=['GET'])def get(): return render_template('home.html')# ... from main.someapp.api import mod as someappmodapp.register_blueprint(someappmod)然后,在其他文件中,我可能会知道要运行什么配置:
# run.pyimport osos.environ["DIAG_CONFIG_MODULE"] = "config.postgres"from main import appapp.run(debug=True)
和
# shell.pyimport osos.environ["DIAG_CONFIG_MODULE"] = "config.postgres"from main import app, dbfrom main.symdiag.models import *from main.auth.models import *print sorted(k for k in locals().keys() if not k.startswith("_"))import IPythonIPython.embed()也许到目前为止最好。



