4

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 the app object, but it doesn't seem to be connecting for some reason. Am I missing something important here?

asked May 1, 2017 at 1:29

1 Answer 1

14

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()
answered May 1, 2017 at 1:34
2
  • Thanks, that was easy. What was also nice about the db.create_all() it is that it seems to be 'idempotent'. Not saying I know that it's that, but just experimented with that code and it creates the tables if they don't exist, but when it is run subsequent times, it just leaves them alone and rows are added to the existing. Commented Jun 7, 2019 at 9:02
  • 1
    @cardamom yes it only creates them once. Though I believe it alters the tables if something has changed in the model. I know some developers run it every time their app initializes. Commented Jun 7, 2019 at 16:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.