如何从 SqlAlchemy 创建和恢复备份? [英] How to create and restore a backup from SqlAlchemy?

查看:81
本文介绍了如何从 SqlAlchemy 创建和恢复备份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Pylons 应用程序,并且正在尝试创建一个简单的备份系统,其中每个表都被序列化并压缩成一个文件供管理员下载,并用于在发生错误时恢复应用程序.

I'm writing a Pylons app, and am trying to create a simple backup system where every table is serialized and tarred up into a single file for an administrator to download, and use to restore the app should something bad happen.

我可以使用 SqlAlchemy 序列化程序,我也可以很好地反序列化它,但我不知道如何将这些更改提交回数据库.

I can serialize my table data just fine using the SqlAlchemy serializer, and I can deserialize it fine as well, but I can't figure out how to commit those changes back to the database.

为了序列化我的数据,我这样做:

In order to serialize my data I am doing this:

from myproject.model.meta import Session
from sqlalchemy.ext.serializer import loads, dumps
q = Session.query(MyTable)
serialized_data = dumps(q.all())

为了测试结果,我继续截断 MyTable,然后尝试使用 serialized_data 进行恢复:

In order to test things out, I go ahead and truncation MyTable, and then attempt to restore using serialized_data:

from myproject.model import meta
restore_q = loads(serialized_data, meta.metadata, Session)

这似乎没有任何作用...事后我尝试调用 Session.commit,分别遍历 restore_q 和添加它们,但似乎没有任何效果.

This doesn't seem to do anything... I've tried calling a Session.commit after the fact, individually walking through all the objects in restore_q and adding them, but nothing seems to work.

我错过了什么?或者有没有更好的方法来做我的目标?我不想掏空直接接触数据库,因为SqlAlchemy 支持不同的数据库引擎.

What am I missing? Or is there a better way to do what I'm aiming for? I don't want to shell out and directly touch the database, since SqlAlchemy supports different database engines.

推荐答案

你必须使用 Session.merge() 方法而不是 Session.add() 将反序列化的对象放回会议.

You have to use Session.merge() method instead of Session.add() to put deserialized object back into the session.

这篇关于如何从 SqlAlchemy 创建和恢复备份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆