Flask-Testing を使用した codegeek の回答については、何をするのか理解できcreateapp()
ません。Flask-SqlAlchemy Introduction into Contextsは、SQLAlchemy オブジェクトをアプリケーションに動的にバインドする方法についての指針を提供してくれました。この場合、テスト アプリケーションにバインドします。
基本的:
- フラスコの sqlalchemy オブジェクトを作成しますが、アプリ オブジェクトは渡さないでください。
- create_app 関数で、テスト アプリケーションを作成し、SQLAlchemy を動的にバインドします。
あなたのmyapp.py :
# don't pass in the app object yet
db = SQLAlchemy()
def create_test_app():
app = Flask(__name__)
app.config['TESTING'] = True
app.config["SQLALCHEMY_DATABASE_URI"] = "xxxxxxtestdatabasexxx"
# Dynamically bind SQLAlchemy to application
db.init_app(app)
app.app_context().push() # this does the binding
return app
# you can create another app context here, say for production
def create_production_app():
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "xxxxxxproductionxxxx"
# Dynamically bind SQLAlchemy to application
db.init_app(app)
app.app_context().push()
return app
次に、Flask-Test Documentation で概説されているように、codegeek のソリューションに従うことができます。
from flask.ext.testing import TestCase
from myapp import create_app, db
class MyTest(TestCase):
# I removed some config passing here
def create_app(self):
return create_test_app()
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
このソリューションの優れた点は、さまざまなアプリケーションを作成し、関数を使用して SQLAlchemy オブジェクトを動的にバインドできることです。各アプリケーションは、さまざまな目的に使用できます。たとえば、1 つは本番用、もう 1 つは単体テスト用です。プロダクションの場合、最上位のフラスコ アプリケーションで create_production_application() を呼び出すことができます。