[FIXED] How to use instance file in flask

Issue

I am using SQLalchemy to create a database in flask. For this, create a project.db file and run the following code:

From Flask Import Flask
Import SQLAlchemy from Flask_sqlalchemy

# create extension
Decibels = SQLAlchemy()
# Create an app
app = Flask(__name__)
# configure the SQLite database relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
# Initialize app with extension
db.init_app(app)

Class User (db.Model):
    id = db.Column(db.Integer, primary_key=True)
    Username = db.Column(db.String, unique=True, nullable=False)
    email = db.string (db.string)

Using app.app_context():
    db.create_all()
 

Running create_table will create a new folder named instance and a new project.db file inside it. As a result my initial project.db does not work and is useless.

So what should I do? Because when I watch different topics and videos this never happens. Thanks in advance!

Solution

Where is project.db located? Keep it in the same folder as the script, or try using an absolute path like this?

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////absolute/path/to/project.db"

Answered By – davie

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published