I have a flask app with SQLAlchemy trying to connect to sqlite app.db file.
When I run the app (python run.py) it says:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
Relevant project structure:
/app
__init__.py
models.py
/db
app.db
run.py
config.py
My run.py file as follows:
from app import create_app
app = create_app()
app.run()
This imports and runs a create_app function from init.py file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from .home.routes import home_bp
from .students.routes import students_bp
from .datasets.routes import datasets_bp
from .reports.routes import reports_bp
def create_app():
"""Create Flask application."""
app = Flask(__name__)
app.config.from_object('config')
# Initialise extensions
db = SQLAlchemy(app)
db.create_all()
with app.app_context():
# Import parts of our application
from .home import routes
from .students import routes
from .datasets import routes
from .reports import routes
# Register Blueprints
app.register_blueprint(home_bp)
app.register_blueprint(students_bp)
app.register_blueprint(datasets_bp)
app.register_blueprint(reports_bp)
return app
Database config is loaded from config.py:
from dotenv import load_dotenv
load_dotenv()
# DB Config
DB_FILE = 'db/app.db'
SQLALCHEMY_DATABASE_URI = 'sqlite:///db/app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
The models.py file:
import db
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
usi = db.Column(db.String(64), index=True)
first_name = db.Column(db.String(256))
last_name = db.Column(db.String(256))
dob = db.Column(db.String(64))
active = db.Column(db.Boolean)
def to_dict(self):
return {
'usi': self.usi,
'first_name': self.first_name,
'last_name': self.last_name,
'dob': self.dob,
'active': self.active
}