How do you set up a Flask application with SQLAlchemy for testing?

前端 未结 3 1720
遇见更好的自我
遇见更好的自我 2020-12-24 12:47

It seems common practice in Flask to start like this:

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
SQLALCHEMY_DAT         


        
3条回答
  •  被撕碎了的回忆
    2020-12-24 13:10

    First, instead of instantiating Flask app directly in your script, you use an application factory. It means you create a function that takes your config file as parameter, and return the instantiated app object. Then, you create the global SQLAlchemy object without parameter, and you configure it when creating the app, as explained here.

    db = SQLAlchemy()
    
    def create_app(configfile):
        app = Flask(__name__)
    
        app.config.from_pyfile(config, silent=True)
        db.init_app(app)
    
        # create routes, etc.
    
        return app
    

    To run the app, you simply do something like:

    app = create_app('config.py')
    app.run()
    

    To run unittests, you can do something like:

    class Test(TestCase):
        def setUp(self):
            # init test database, etc.
            app = create_app('test_config.py')
            self.app = app.test_client()
        def tearDown(self):
            # delete test database, etc.
    

    In my case, I'm using SQLAlchemy directly with scoped_session instead of Flask-SQLAlchemy. I did the same, but with Lazy SQLAlchemy setup.

提交回复
热议问题