SQLAlchemy会话:会话之间的持久性?

时间:2015-06-18 04:32:46

标签: python session sqlalchemy

我有一个基本脚本,它创建一组Player类对象,然后将它们保存到我的DB中(使用SQLAlchemy)。我的主要方法看起来像这样:

def main():
    #create engine (for use by base and session)
    engine = databaseFunctions.createEngine()
    #create session
    session = databaseFunctions.createSession(engine)
    databaseFunctions.updateEntireDB(allPlayers, session)

现在我已将其更改为:

def main():
    #create engine (for use by base and session)
    engine = databaseFunctions.createEngine()
    #create session
    session = databaseFunctions.createSession(engine)
    #list all players in DB
    databaseFunctions.allPlayers(session)

在运行带有第一个定义的main()之后,我关闭了我的shell,重新打开并使用新定义运行main()。我的所有数据库对象似乎都正确打印(所以看起来它们会在会话创建之间保持不变)。

运行一次函数到#34;初始化DB"是否正常?然后只更新它(假设它只需要更新)?在使用初始化代码运行它之后改变我的主程似乎是不好的做法...

1 个答案:

答案 0 :(得分:1)

对于您的第一个问题,是的,这是完全正常的,但您肯定希望将其作为应用程序的一部分提供初始化/迁移步骤。假设您想将此作为databaseFunction模块的一部分,您可能需要这样的内容:

databaseFunctions.py

def checkDB(engine):
    session = createSession(engine)
    # use the session here to check the database
    # return True if the tables for your app are properly created/updated

# ... your database functions.

在入口点模块中:

def main():
    engine = databaseFunctions.createEngine()
    session = databaseFunctions.createSession(engine)

    # could be rolled into databaseFunctions
    if not databaseFunctions.checkDB():
        databaseFunctions.updateEntireDB(allPlayers, session)

    # list all players in DB
    databaseFunctions.allPlayers(session)

您可以考虑查看sqlalchemy Session API上的文档。

相关问题