"RuntimeError: Working outside of application context" in Flask

Question:

I am learning flask using this tutorial. When I try to execute db.create_all() in the interactive python environment in VS Code, I get Working outside of application context error. According to this solution, I have done everything correct. I am not able to find the error in my code. Can someone please help me?
Following is the code:

from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False)
    completed = db.Column(db.Integer, default =0)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Task %r>' % self.id

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True)

The interactive python steps:

  1. from app import db
  2. db.create_all()

The folder structure looks like:

enter image description here

Asked By: Aim

||

Answers:

In this case you need to push application context.

# debug.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# change sqlalchemy log level
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)

from console:

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from debug import app, db
../env/lib/python3.10/site-packages/flask_sqlalchemy/__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
>>> with app.app_context():
...     db.create_all()  # you work inside app context
... 
INFO:sqlalchemy.engine.Engine:BEGIN (implicit)
INFO:sqlalchemy.engine.Engine:PRAGMA main.table_info("todo")
INFO:sqlalchemy.engine.Engine:[raw sql] ()
DEBUG:sqlalchemy.engine.Engine:Col ('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk')
INFO:sqlalchemy.engine.Engine:PRAGMA temp.table_info("todo")
INFO:sqlalchemy.engine.Engine:[raw sql] ()
DEBUG:sqlalchemy.engine.Engine:Col ('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk')
INFO:sqlalchemy.engine.Engine:
CREATE TABLE todo (
    id INTEGER NOT NULL, 
    PRIMARY KEY (id)
)


INFO:sqlalchemy.engine.Engine:[no key 0.00007s] ()
INFO:sqlalchemy.engine.Engine:COMMIT
Answered By: Danila Ganchar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.