95

I'm trying to separate my Flask-SQLAlchemy models into separate files. When I try to run db.create_all() I get No application found. Either work inside a view function or push an application context.

shared/db.py:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from shared.db import db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string'
db.init_app(app)

user.py:

from shared.db import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email_address = db.Column(db.String(300), unique=True, nullable=False)
    password = db.Column(db.Text, nullable=False)
davidism
  • 121,510
  • 29
  • 395
  • 339
Omegastick
  • 1,773
  • 1
  • 20
  • 35

1 Answers1

192

Use with app.app_context() to push an application context when creating the tables.

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string'
db.init_app(app)

with app.app_context():
    db.create_all()
davidism
  • 121,510
  • 29
  • 395
  • 339
Shtlzut
  • 2,174
  • 1
  • 16
  • 14
  • I'm really grateful thank you (+1) – A.Sana Sep 02 '20 at 12:48
  • 1
    Hi, even after putting this i am having issue. Can you please help ? – Mervin Hemaraju Nov 25 '20 at 17:41
  • 2
    This helped me after the app = create_app() app.app_context().push() I tried to do it from the console according the SqlAlchemy it can't automatically bind your db to the application - further info here: https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/ – Anna Semjén Dec 04 '20 at 11:46
  • @AnnaSemjén have you found a solution, I added create_app() to flask `__init__py` after it I can create tables and working into flask app, but in terminal I cannot get `User.query.all()` – dannisis Apr 19 '21 at 00:12
  • 3
    I think you need to create the context too - If I remember correctly - >>> from yourapp import create_app >>> app = create_app() >>> app.app_context().push() – Anna Semjén Apr 20 '21 at 12:11
  • what about dropping table? I getting this error when I want to call drop_all() function – Hosein Aqajani Apr 30 '21 at 11:25
  • Not working for me. I'm working inside the app file where the context is readily available. Where do we add this? In the worker I cannot add it due to circ dep error. I've added it many places to test anyway, and it doesn't work. Only the worker cannot access context, all other okay. What else can I do? – Mote Zart Apr 29 '22 at 20:46