I have a Flask application with SQLAlchemy that was working fine until now. Suddenly, while the instance folder is being created, the database file isn't. I tried db.create_all() via shell, it works fine.
Error:
OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
\[SQL: SELECT user.id AS user_id, user.username AS user_username, user.name AS user_name, user.email AS user_email, user.password AS user_password
FROM user
WHERE user.email = ?
LIMIT ? OFFSET ?\]
\[parameters: ('[email protected]', 1, 0)\]
Project Structure:
v1/
app/
__init__.py
models.py
routes.py
instance/ # Created but empty
config.py
run.py
My code:
app/__init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import DevelopmentConfig
app = Flask(__name__)
app.config.from_object(DevelopmentConfig)
db = SQLAlchemy(app)
app.app_context().push()
from app import routes
from app.models import User
config.py:
class Config:
SQLALCHEMY_DATABASE_URI = 'sqlite:///quizmaster.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(Config):
DEBUG = True
SECRET_KEY = 'super-secret-key'
models.py:
from app import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(15), unique=True, nullable=False)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(80), nullable=False)
run.py:
from app import app, db
from app.models import User
from sqlalchemy import or_
if __name__ == '__main__':
db.create_all()
# Create admin user if not exists
admin_exists = User.query.filter(
or_(
User.username == 'admin',
User.email == '[email protected]'
)
).first()
if not admin_exists:
admin = User(
id=0,
username='admin',
name='admin',
email='[email protected]',
password='admin123'
)
db.session.add(admin)
db.session.commit()
app.run(debug=True)
What's strange is that this code was working fine until now. If i run this now, only the instance folder gets created, the database was not created. I tried deleting the instance folder and made it recreate, still same issue.
db.create_all()is not initializing the database, but there is no indication as to why. Are you sure there should not be a call todb.init_app(app)before the create call?db.create_all()before the other initializations.if __name__ == '__main__', since I run my app usingflask run. My issue is resolved now.