Making a database connection using SQLAlchemy and sqlite3 database. my expected behaviour was the engine will make a database file in my directory folder. However the engine didn't create a database file, yet my app connected to a database with no file.
here's the App Factory file:
from flask import Flask
from .config import SECRET_KEY
from .extensions import db
from .blueprints.user import main
def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = SECRET_KEY
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////database.db"
db.init_app(app)
app.register_blueprint(main)
@app.route('/test')
def test():
return 'bruh'
with app.app_context():
from .models.users import Users
db.create_all()
return app
app/models/users.py
from ..extensions import db
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
nama_pembeli = db.Column(db.String, nullable=False)
email = db.Column(db.String)
again there aren't a database file in my app directory, but when i checked into the Flask shell, the table's are there. i can even insert data into it.
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
App: app.app
Instance: B:\code\instance
>>> Users
<class 'app.app.models.users.Users'>
>>> Users.query.all()
[<Users 1>, <Users 2>]
there are Instance: B:\code\instance
in the shell but the directory is not there. is there something wrong with the code or is this a bug?
Based on this issue on Flask-SQLAlchemy I figured out that SQLAlchemy created the database file based on flask app.instance_path
variable. So what I have to do was change the variable since it was set outside the project directory.
from flask import Flask
from .config import SECRET_KEY
from .extensions import db
from .blueprints.users import main
import os
def create_app():
abs_instance_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'instance')) #<--- this will be the instance directory
app = Flask(__name__, instance_path=abs_instance_path)
app.config["SECRET_KEY"] = SECRET_KEY
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db.init_app(app)
app.register_blueprint(main)
@app.route('/test')
def test():
return 'bruh'
with app.app_context():
from .models.users import Users
db.create_all()
return app
note that flask only accept absolute path as an argument for app.instance_path