Configure Python Flask App to use “create_app” factory and use database in model class

前端 未结 1 1354
野性不改
野性不改 2020-12-18 07:47

I\'m having trouble getting my app to start when using a create_app() function. I\'m new to building apps to this way and from all of my research it seems that

相关标签:
1条回答
  • 2020-12-18 08:16

    I've started migrating toward using the form of the create_app pattern that Miguel Grinberg illustrations in part XI of his Flask Mega-Tutorial.

    In your case, the reference to your db object locked in a local variable inside of create_app. The trick is to get it visible. Consider this scheme, which I use with SQLAlchemy, and which you would adapt to use your wrapper:

    main.py
    config.py
    tests.py
    app/
        __init__.py
    

    First, the default configuration which looks something like this (trimmed for brevity)

    # config.py
    ...
    class Config:
        TESTING = False
        SQLALCHEMY_DATABASE_URI = ...
        ...
    

    The config will be used as a default by the factory.

    # app/__init__.py
    ...
    db = SQLAlchemy()  # done here so that db is importable
    migrate = Migrate()
    
    def create_app(config_class=Config):
        app = Flask(__name__)
        app.config.from_object(config_class)
        db.init_app(app)
        migrate.init_app(app, db)
        ... register blueprints, configure logging etc.
        return app
    

    Note that from app import db works.

    # main.py
    from app import create_app
    app = create_app()
    

    And thenFLASK_APP=main.py venv/bin/flask run.

    And for testing, a subclass of Config uses an in-memory database (and makes other tweaks to avoid hitting external services).

    # tests.py
    ...
    class TestConfig(Config):
        TESTING = True
        SQLALCHEMY_DATABASE_URI = 'sqlite://'
    
    class ExampleTests(unittest.TestCase):
        def setUp(self):
            self.app = create_app(TestConfig)
            # See Grinberg's tutorial for the other essential bits
    
    0 讨论(0)
提交回复
热议问题