sqlalchemy 保存到内存

Sqlalchemy save to memory

我的应用程序需要在离线时保存更改并在重新连接时上传它们。

我知道我也可以使用 SQLite、json 等来保存它们,但如果我能让 sqlalchemy 提交到内存而不是减少代码,我真的很喜欢它。我不担心 atm 断电或程序崩溃。

我假设使用 sessions.add() 会执行此操作,并且当它重新连接时 sessions.commit() 会提交所有更改,但当我添加另一个时它似乎被覆盖了。

这可以吗?

你可以使用 SQLite 做一个 in-memory database:

engine = create_engine('sqlite://')

看看您的 autoflush 设置:

When True, all query operations will issue a flush() call to this Session before proceeding. This is a convenience feature so that flush() need not be called repeatedly in order for database queries to retrieve results. It’s typical that autoflush is used in conjunction with autocommit=False. In this scenario, explicit calls to flush() are rarely needed; you usually only need to call commit() (which flushes) to finalize changes.

它可能对您不利,因为 add 指出:

Place an object in the Session.
Its state will be persisted to the database on the next flush operation.
Repeated calls to add() will be ignored. The opposite of add() is expunge().

其他流行的短期数据存储选项包括 Redis