Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Flask - How to access sqlite database.db on pythonanywhere.com without specifying its directory?

I am using flask and sqlite3 on https://www.pythonanywhere.com. In my own machine, when I test the application, I do not need to specify the directory of the database for example db = sqlite3.connect("database.db") and it works perfectly. While on pythonanywhere, I would need to change it to db = sqlite3.connect("/path/to/database.db") because when I do not change I will get this error:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

In /var/log/<application>.pythonanywhere.com.error.log, I get:

OperationalError: no such table: <table-name>

And I found an empty database.db in my home folder at pythonanywhere (which means the application created it, right?) and the database.db I created is in the projects folder

Is there any way to specify the directory in order for it to work perfectly both in my machine and on pythonanywhere without changing the path?

like image 737
Austin Imperial Avatar asked Feb 09 '23 04:02

Austin Imperial


1 Answers

In your db file, try this way:

from os import path

ROOT = path.dirname(path.realpath(__file__))

...
db = sqlite3.connect(path.join(ROOT, "database.db"))
...

Instead of directly pointing out the path, the ROOT always point to the directory of your file that contains the db, then you should get the right location for your database.

like image 53
lord63. j Avatar answered Feb 12 '23 12:02

lord63. j