'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:////"))):
    db.create_all()
else:
    print("database already exists")


Solution 1:[1]

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__":
   db.create_all()
   Do something here

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1