I am using flask_sqlalchemy to manage a database for a small web app. I have been using sqlite locally, but am now migrating to a postgresql database as it is the case in production environment.
Currently, the app has some logic where if the database does not exist, I read in some csv files and populate the tables:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
path_to_db = 'data/database.db'
db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{path_to_db}'
db.init_app(app)
if not path.exists(path_to_db):
db.create_all(app)
# Read in csv files and add to database
Now I have created a postgresql database called database using pgAdmin and changed the code to:
path_to_db = 'database'
#...
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://postgres:postgres@localhost:5432/{path_to_db}'
# >> How do I check whether this database is empty?
# if not path.exists(path_to_db):
# Read in csv files and add to database
In the original sqlite code, it creates a database called database.db which I then check if exists. If it doesn't I create one, and read in csv files. However I am confused about on how to implement this logic with postgresql, and how to check if the database is empty.
Any suggestions?
create_allhas acheckfirstargument that defaults toTrue, and it will skip the creation of table for the database. Moreover, the database in postgresql is typically created outside the application as permissions are typically involved - if the database is not available,db.init_app(app)will simply fail.after_createevent handler and add the data as appropriate.after_createseems like a good way here. However I have several tables, and my understanding is thatdb.create_all()will create all of them. Is this done at the same time? I would like the event handler to trigger if and only when all tables were just created.db.create_all()will only create tables that are missing, so if your database has some of your tables already, your method will try to add the data regardless of the schema(s) of the pre-existing table(s), while doing it with theafter_createevent should only affect each individual table that got freshly created (so only insert data for that table associated with the event).