0

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
        }
TimothyAURA
  • 1,329
  • 5
  • 21
  • 44
  • Does this answer your question? [Sqlite3, OperationalError: unable to open database file](https://stackoverflow.com/questions/4636970/sqlite3-operationalerror-unable-to-open-database-file) – VPfB Dec 21 '21 at 08:57
  • No it doesn't unfortunately, but thanks. Update: When I comment out db.create_all() the error disappears. Am I using this function in the wrong place? Things were working OK before I refactored to blueprints. – TimothyAURA Dec 21 '21 at 09:17
  • If the errors disappear after commenting out this line, then the problem may be that you are trying to overwrite an already existing database. You should perhaps consider putting a test that checks if the database already exists before generating it. – Tobin Dec 21 '21 at 12:16
  • I have deleted the database file to conduct a test, yet it says cannot open database. How could this be? – TimothyAURA Dec 21 '21 at 14:18

0 Answers0