I have been learning python recently and practiced a couple of tutorials and its been going fine, till I have divided my application to sub modules to make it easier to maintain using blueprints, after doing so the application crashed and throw the following error: OperationalError: (sqlite3.OperationalError) no such table, here is how im dividing my application:
-instance
-flask.cfg
-app
- static // Folder for css
- templates // Folder for common html files
-__init__.py // to init the app
-module1
-__init__.py // to register module blueprint
-subModule1
-subModule1 Group1
-templates
-htmls files
-__init__.py file //to register group1 blueprint
-Group1Form
-Group1Model
-Group1View
-subModule1 Group2
-templates
-htmls files
-__init__.py file //to register group2 blueprint
-Group2Form
-Group2Model
-Group2View
-subModule2
....
-main.py
The application run fine when I use flask run
but I have an issue when I use db.session.add()
method with the exception that the table was not found. I have tried many solutions to this issue but no luck. here is some links for the same issue:
OperationalError: (sqlite3.OperationalError) no such table: user
https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/
Python sqlite3.OperationalError: no such table:
'No application found. Either work inside a view function or push an application context.'
Here is the flask.cfg file:
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = os.urandom(32)
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.abspath('app.db')
And here is how I am initializing the app in the main __init__.py
file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_filename=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile(config_filename)
initialize_extensions(app)
register_blueprints(app)
def create_app(config_filename=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile(config_filename)
initialize_extensions(app)
register_blueprints(app)
return app
def initialize_extensions(app):
db.init_app(app)
with app.app_context():
db.create_all()
def register_blueprints(app):
from app.module1.config.university import university_blueprint
app.register_blueprint(university_blueprint)
from app.module1.config.department import department_blueprint
app.register_blueprint(department_blueprint)
from app.module1.authors.author import author_blueprint
app.register_blueprint(author_blueprint)
from app.module1.authors.publications import publications_blueprint
app.register_blueprint(publications_blueprint)