Creating a database in flask sqlalchemy
You either have to create a request or you have to create the models with sqlalchemy directly. We do something similar at work and chose the former.
Flask lets you create a test request to initialize an app. Try something like
from application.database import db
from application.server import app
with app.test_request_context():
db.init_app(app)
db.create_all()
Copernicus
Updated on June 04, 2022Comments
-
Copernicus almost 2 years
I'm building a Flask app with Flask-SQLAlchemy and I'm trying to write a script that will create a Sqlite3 database without running the main application. In order to avoid circular references, I've initialized the main Flask app object and the SQLAlchemy database object in separate modules. I then import and combine them in a third file when running the app. This works fine when I'm running the app, as the database is built and operates properly when create rows and query them. However, when I try to import them in another module, I get the following error:
RuntimeError: application not registered on db instance and no applicationbound to current context
My code looks like the following:
root/create_database.py
from application.database import db from application.server import app db.init_app(app) db.create_all()
root/run.sh
export FLASK_APP=application/server.py flask run
root/application/init.py
from database import db from server import app db.init_app(app) from routes import apply_routes apply_routes(app)
root/application/database.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
root/application/server.py
from flask import Flask import os app = Flask(__name__) path = os.path.dirname( os.path.realpath(__file__) ) database_path = os.path.join(path, '../mydb.sqlite') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + database_path
root/application/models/init.py
from user import User
root/application/models/user.py
from application.database import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) password = db.Column(db.String(120)) def __init__(self, username, password): self.username = username self.password = password
In my create_database.py script I'm trying to make sure that the SQLAlchemy
db
instance is configured with the config details from theapp
object, but it doesn't seem to be connecting for some reason. Am I missing something important here?