Best way to check if database already exists with flask-sqlalchemy, otherwise create


I have a database app, and want to create the tables and database on the fly when starting the app for the first time. If the app is restarted, it should only create the database and tables if they do not exist, otherwise ignore this creation. I have a few questions.
1.) Is this a proper way of dealing with dataset creation in Flask/SQL?
2.) If there are other ways, how to prevent Flask from overwriting existing .db file?
3.) Is the approach written below a valid approach?

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, request, redirect, g
import sqlite3
import os.path
import os
#from forms import RegistrationForm, LoginForm

#from flaskblog import db
#Get working directory
file_path = os.path.abspath(os.getcwd()+"/DATA/site.db")
app =  Flask(__name__)
app.config["SECRET_KEY"] = "someweirdsecretkeywhatevermaybeuuid4"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///DATA/site.db"
db = SQLAlchemy(app)

#Define tables we need to have in databases
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), unique=False, default="default.jpg")
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

if not os.path.exists(("/"+str(db.engine.url).strip("sqlite:////"))):
    print("database already exists")


You don’t have to import os and check whether the DB file is there or not.
Call db.create_all() method inside here:-

if __name__ == "__main__":
   Do something here

It will create sqlite3 DB once. If you are using another DB, this will create the tables once.

Answered By – Fasil K

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published