title: Creating a database in flask sqlalchemy
body: <p>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:</p>
  
  <pre><code>RuntimeError: application not registered on db instance and no applicationbound to current context
  </code></pre>
  
  <p>My code looks like the following:</p>
  
  <p>root/create_database.py</p>
  
  <pre><code>from application.database import db
  from application.server import app
  
  db.init_app(app)
  
  db.create_all()
  </code></pre>
  
  <p>root/run.sh</p>
  
  <pre><code>export FLASK_APP=application/server.py
  flask run
  </code></pre>
  
  <p>root/application/<strong>init</strong>.py</p>
  
  <pre><code>from database import db
  from server import app
  
  db.init_app(app)    
  
  from routes import apply_routes   
  apply_routes(app)
  </code></pre>
  
  <p>root/application/database.py</p>
  
  <pre><code>from flask_sqlalchemy import SQLAlchemy
  db = SQLAlchemy()
  </code></pre>
  
  <p>root/application/server.py</p>
  
  <pre><code>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
  </code></pre>
  
  <p>root/application/models/<strong>init</strong>.py</p>
  
  <pre><code>from user import User
  </code></pre>
  
  <p>root/application/models/user.py</p>
  
  <pre><code>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
  </code></pre>
  
  <p>In my create_database.py script I'm trying to make sure that the SQLAlchemy <code>db</code> instance is configured with the config details from the <code>app</code> object, but it doesn't seem to be connecting for some reason. Am I missing something important here?</p>