Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite database backup and restore in flask sqlalchemy

I am using flask sqlalchemy to create db which in turns create a app.db files to store tables and data. Now for the backup it should be simple to just take a copy of app.db somewhere in the server. But suppose while the app is writing data to app.db and we make a copy at that time then we might have inconsistent app.db file.

How do we maintain the consistency of the backup. I can implement locks to do so. But I was wondering on standard and good solutions for database backup and how is this implemented in python.

like image 959
Ankit Vallecha Avatar asked May 01 '18 08:05

Ankit Vallecha


People also ask

How do I use SQLAlchemy with flask?

After configuring SQLAlchemy by setting a database URI and disabling tracking, you create a database object using the SQLAlchemy class, passing the application instance to connect your Flask application with SQLAlchemy. You store your database object in a variable called db. You’ll use this db object to interact with your database.

How do I open a SQLite3 database in flask?

Open a file named init_db.py inside your flask_app directory: You first import the sqlite3 module. You open a connection to a database file named database.db, which will be created once you run the Python file. Then you use the open () function to open the schema.sql file.

How do I backup a SQLite database?

You can also backup a SQLite database using the SQLite command. This output or backup file in this way will contain all the necessary SQL codes to reconstruct the database. Run the following command to backup the test.db database file to backup.sql SQL file:

How to create a SQLite database using SQLAlchemy?

In your app.py file import SQLAlchemy as shown in the below code. We also need to add a configuration setting to our application so that we can use SQLite database in our application. We also need to create an SQLAlchemy database instance which is as simple as creating an object. In sqlalchemy we use classes to create our database structure.


1 Answers

SQLite has the backup API for this, but it is not available in the built-in Python driver.

You could

  • use the APSW library for the backup; or
  • execute the .backup command in the sqlite3 command-line shell; or
  • run BEGIN IMMEDIATE to prevent other connections from writing to the DB, and copy the file(s).
like image 61
CL. Avatar answered Oct 17 '22 12:10

CL.