Home > Back-end >  sqlalchemy does not initialize the database
sqlalchemy does not initialize the database

Time:05-12

I have created a models.py file describing my schema. I am using the code below to create the DB and initialize it with the model.py schema. When I call the create_app function a new sqlite file gets create but it is empty. It is not picking up the schema from my models.py file.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils.functions import database_exists

db = SQLAlchemy()
DB_NAME = "database.db"


def create_app():
    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'

    if not database_exists(app.config['SQLALCHEMY_DATABASE_URI']):
        db.init_app(app)
        db.create_all(app=app)
        print(f'Created Database Successfully!!')

    return app

models.py

from .main import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))

CodePudding user response:

happened to me with missing init.py file in the package, maybe thats the case

CodePudding user response:

After I imported the models file first, the DB was created sucessfully.

  • Related