How to use instance file in flask

Question:

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

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
# initialize the app with the 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.Column(db.String)

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

When I run create_table, it creates me a new folder named instance and a new project.db file in it. The result is that my first project.db does not work and is useless.

What must I do then ? Because when looking at different topic and videos this never happens. Thanks in advance !

Asked By: Ces

||

Answers:

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
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.