pythonpython-3.xsqlitesqlalchemy

sqlite3.OperationalError: unable to open database file in virtual enviornment


I am trying to access a database named 'app.db' through sqlite3.connect() using a config with the URI of the file. I am also running this in a virtual enviornment and I am on windows.

Here is where I am trying to access the db

from flask import current_app

def connect_db():

    return sqlite3.connect(current_app.config['SQLALCHEMY_DATABASE_URI'])

This is how I initalize the db which is in my init

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os
from .db import db, init_app, close_connection, get_db

import click
from flask.cli import with_appcontext

def create_app(test_config=None):
    print("initalized")
    app = Flask(__name__, instance_relative_config=True)
    db_path = os.path.join(app.instance_path, 'app.db')
    app.secret_key = 'dev'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    @click.command('init-db')
    @with_appcontext
    def init_db_command():
        """Clear the existing data and create new tables."""
        db.drop_all()
        db.create_all()
        print(db_path)
        click.echo('Initialized the database.')
    
    app.cli.add_command(init_db_command)
    
Here is the full trace
[2025-04-09 11:17:40,893] ERROR in app: Exception on /auth/register [GET]
Traceback (most recent call last):
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\venv\Lib\site-packages\flask\app.py", line 1511, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\venv\Lib\site-packages\flask\app.py", line 919, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\venv\Lib\site-packages\flask\app.py", line 915, in full_dispatch_request
    rv = self.preprocess_request()
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\venv\Lib\site-packages\flask\app.py", line 1291, in preprocess_request
    rv = self.ensure_sync(before_func)()
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\flaskr\__init__.py", line 31, in load_db
    get_db()
    ~~~~~~^^
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\flaskr\db.py", line 16, in get_db
    g.db = connect_db()
           ~~~~~~~~~~^^
  File "C:\Users\iansh\OneDrive\Desktop\my_code\webappflask\flaskr\db.py", line 21, in connect_db
    return sqlite3.connect('sqlite:///C:\\Users\\iansh\\OneDrive\\Desktop\\my_code\\webappflask\\instance\\app.db')
           ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: unable to open database file
127.0.0.1 - - [09/Apr/2025 11:17:41] "GET /auth/register HTTP/1.1" 500 -

I have checked that the database file is not corrupted by using sqlite3's command line, python -m sqlite3 {file}. I then used the command

I have tried replacing current_app.config['SQLALCHEMY_DATABASE_URI'] with the absolute path.

I have also checked on the properties of the database file that it can read and write.

After all of this, I still go the same error


Solution

  • Turns out you're not supposed to add

    'sqlite:///'
    

    in front of the path, and instead, the full path. This is because 'sqlite:///' is used for SQLAlchemy connections

    Here is what I changed in my code at the top:

    import sqlite
    import os
    
    def connect_db():
        db_path = os.path.join(current_app.instance_path, 'app.db')
        print(f"path: {db_path}")
        conn = sqlite3.connect(db_path)
        conn.row_factory = sqlite3.Row
        return conn