0

I have a Flask app where I call sqlite3.connect('database.db'). This causes the error: sqlite3.OperationalError: unable to open database file. This seems to work fine when testing on Windows but not on Debian.

My project is organized as so:

flaskapp.wsgi
flask_app
    __init__.py
    init_db.py
    database.db

init_db.py creates the database with a table and an entry for that table, running that works just fine. __init__.py has the flask app itself with the following method inside it:

def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn

The stacktrace ends at the first line of this method with the error previously mentioned. For more context the app works when I test it out with the development server on Windows 10. But not on my webserver which is running Debian and Apache2.

I expect it to simply connect and do all the database stuff I want to do. I suspect it has something to do with Apache2 having some default behavior I didn't expect in relation to Flask. It doesn't appear to be an issue with file permissions, I tried everything that was recommended in this answer: https://stackoverflow.com/a/4637055/21932305 but I still have the error.

Lacey
  • 23
  • 3
  • Have you tried putting `./database.db` as the path? And in your debian environment what command are you invoking to start flask app and from which folder?? – Kartoos May 21 '23 at 17:03
  • @Kartoos I tried that, same error. I use `systemctl start apache2` to start it from `/var/www/flask_app/flask_app` – Lacey May 21 '23 at 18:07
  • I have a feeling that your relative path is getting messed up when you are running on Apache. Can you try to print `here` variable in your code: `here = os.path.dirname(__file__)` – Kartoos May 21 '23 at 18:11
  • Most likely your app does not have permission to write into the app's current working directory. – John Hanley May 21 '23 at 18:59
  • @JohnHanley `flask_app` and `database.db` have `www-data` as their owners which according to the list of processes is what is running Apache2 – Lacey May 21 '23 at 19:47
  • @Kartoos The output of that is `/var/www/flask_app/flask_app` the directory `__init__.py` is sitting in. I tried `./flask_app/database.db` too and still no luck. – Lacey May 21 '23 at 19:50
  • Using the full path seems to work. I don't like that solution much but it'll do I suppose! – Lacey May 21 '23 at 20:05
  • You should never allow writing to the same directory as your source code. That is one way that sites are breached. Your database should be stored in a directory outside of the site with correct ownership and permissions. – John Hanley May 21 '23 at 20:24

0 Answers0