简体   繁体   English

使用flask-sqlalchemy检查数据库是否已存在的最佳方法,否则创建

[英]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? 1.) 这是在 Flask/SQL 中处理数据集创建的正确方法吗? 2.) If there are other ways, how to prevent Flask from overwriting existing .db file? 2.) 如果有其他方法,如何防止 Flask 覆盖现有的 .db 文件? 3.) Is the approach written below a valid approach? 3.) 下面写的方法是有效的方法吗?

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

You don't have to import os and check whether the DB file is there or not.您不必导入 os 并检查数据库文件是否存在。 Call db.create_all() method inside here:-在这里调用 db.create_all() 方法:-

if __name__ == "__main__":
   db.create_all()
   Do something here

It will create sqlite3 DB once.它将创建一次 sqlite3 数据库。 If you are using another DB, this will create the tables once.如果您使用的是另一个数据库,这将创建一次表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM