我如何懒惰初始化SQLAlchemy

2024-06-02 05:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Flask和SQL炼金术创建一个Web应用程序。 包结构如下所示:

在运行服务器.py在

runserver.py
--- skeleton
    --- filters
    --- helpers
    --- models
    --- modules
        --- admin
        --- api
        --- debug
        --- frontend
    --- static
    --- templates
--- tests

我知道如何延迟加载作用域会话。但在正常情况下我该怎么做呢?在

我在我的应用程序的基本包中的init帴文件中有一个create_uapp函数。在

我的初始文件如下所示:

^{pr2}$

我不能使用烧瓶炼金术,因为其他模块不支持它,模型会变得一团糟。在

在需要时初始化数据库并执行如下导入的最佳做法是什么: 从骨架导入数据库

谢谢分享你的想法


Tags: 文件py服务器web数据库应用程序flasksql
1条回答
网友
1楼 · 发布于 2024-06-02 05:06:07

好吧。我想我也是自己想出来的。 我现在正在使用这个片段。如果你有更好的主意,请告诉我

Base = declarative_base()
engine = None
sessionmaker = sessionmaker()
db = scoped_session(sessionmaker)

def configure_engine(url):
    global sessionmaker, engine, db

    engine = create_engine(url)
    db.remove()
    sessionmaker.configure(bind=engine)

def create_app(name=__name__, configuration=None):
    from .modules import admin
    from .modules.admin.models import User

    app = Flask(name, static_path='/static', template_folder=template_dir)
    load_config(app, configuration)
    celery.config_from_object(app.config)
    configure_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    filters.init_app(app)
    register_local_modules(app)
    admin.init_app(app)
    login_manager.init_app(app)
    @login_manager.user_loader
    def load_user(id):
        return db.query(User).get(id)

    # Enable the DebugToolbar
    if app.config['DEBUG_TOOLBAR']:
        toolbar = DebugToolbarExtension(app)

    return app

相关问题 更多 >