How do I split Flask models out of app.py without passing db object all over?

前端 未结 2 1232
闹比i
闹比i 2021-01-02 06:14

I\'d like to use Flask-Migrate and am looking at their example:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script imp         


        
2条回答
  •  被撕碎了的回忆
    2021-01-02 06:44

    Partitioning such a small application into modules is tricky, because you find a lot of cases where the two modules that you create need to mutually import each other, creating circular dependencies.

    I recommend that you look at how you can structure a larger application properly, using an app factory function and delayed initialization of all extensions. An example application that does this is the Flasky app featured in my book.

    All that said, it is possible to separate the application into two parts, you just need to be careful with where you place the import statements. In the example below, I decided to move the creation of the db instance and the User model into a models.py file.

    Here is the main application's module:

    from flask import Flask
    from flask.ext.script import Manager
    from flask.ext.migrate import Migrate, MigrateCommand
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
    
    from models import db  # <-- this needs to be placed after app is created
    migrate = Migrate(app, db)
    
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)
    
    if __name__ == '__main__':
        manager.run()
    

    And here is models.py:

    from __main__ import app
    from flask.ext.sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy(app)
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(128))
    

    Here the main module will create app, and only then will import models.py. When models.py tries to import app from the main module, it has already been created. If you move from models import db to the top of the file with the other imports this code breaks.

提交回复
热议问题