Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and restore a backup from SqlAlchemy?

Tags:

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.

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()) 

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) 

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.

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.

like image 840
swilliams Avatar asked May 07 '10 06:05

swilliams


People also ask

Is SQLAlchemy good for ETL?

One of the key aspects of any data science workflow is the sourcing, cleaning, and storing of raw data in a form that can be used upstream. This process is commonly referred to as “Extract-Transform-Load,” or ETL for short.

How do I create a database using SQLAlchemy?

Constructor takes name, type and other parameters such as primary_key, autoincrement and other constraints. The create_all() function uses the engine object to create all the defined table objects and stores the information in metadata. Complete code is given below which will create a SQLite database college.

Is flask-SQLAlchemy the same as SQLAlchemy?

What is Flask-SQLAlchemy? Flask-SQLAlchemy is an extension for Flask that aims to simplify using SQLAlchemy with Flask by providing defaults and helpers to accomplish common tasks. One of the most sought after helpers being the handling of a database connection across the app.

Is SQLAlchemy worth learning?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.


1 Answers

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

like image 180
Denis Otkidach Avatar answered Sep 21 '22 20:09

Denis Otkidach